import { dataSource } from "../data-source"; import { role } from "../entity/role"; import { user } from "../entity/user"; import InternalException from "../exceptions/internalException"; export default abstract class UserService { /** * @description get users * @returns {Promise>} */ static async getAll(): Promise> { return await dataSource .getRepository(user) .createQueryBuilder("user") .leftJoinAndSelect("user.roles", "roles") .leftJoinAndSelect("user.permissions", "permissions") .leftJoinAndSelect("roles.permissions", "role_permissions") .getMany() .then((res) => { return res; }) .catch((err) => { throw new InternalException("users not found", err); }); } /** * @description get user by id * @param id number * @returns {Promise} */ static async getById(id: number): Promise { return await dataSource .getRepository(user) .createQueryBuilder("user") .leftJoinAndSelect("user.roles", "roles") .leftJoinAndSelect("user.permissions", "permissions") .leftJoinAndSelect("roles.permissions", "role_permissions") .where("user.id = :id", { id: id }) .getOneOrFail() .then((res) => { return res; }) .catch((err) => { throw new InternalException("user not found by id", err); }); } /** * @description get user by username * @param username string * @returns {Promise} */ static async getByUsername(username: string): Promise { return await dataSource .getRepository(user) .createQueryBuilder("user") .select() .where("user.username = :username", { username: username }) .getOneOrFail() .then((res) => { return res; }) .catch((err) => { throw new InternalException("user not found by username", err); }); } /** * @description get users by mail or username * @param username string * @param mail string * @returns {Promise>} */ static async getByMailOrUsername(mail?: string, username?: string): Promise> { return await dataSource .getRepository(user) .createQueryBuilder("user") .select() .where("user.mail = :mail", { mail: mail }) .orWhere("user.username = :username", { username: username }) .getMany() .then((res) => { return res; }) .catch((err) => { throw new InternalException("user not found by mail or username", err); }); } /** * @description get count of users * @returns {Promise} */ static async count(): Promise { return await dataSource .getRepository(user) .createQueryBuilder("user") .select() .getCount() .then((res) => { return res; }) .catch((err) => { throw new InternalException("could not count users", err); }); } /** * @description get roles assigned to user * @param userId number * @returns {Promise>} */ static async getAssignedRolesByUserId(userId: number): Promise> { return await dataSource .getRepository(user) .createQueryBuilder("user") .leftJoinAndSelect("user.roles", "roles") .leftJoinAndSelect("roles.permissions", "role_permissions") .where("user.id = :id", { id: userId }) .getOneOrFail() .then((res) => { return res.roles; }) .catch((err) => { throw new InternalException("could not get roles for user", err); }); } }