All files / services/user user.service.ts

85.19% Statements 23/27
50% Branches 1/2
83.33% Functions 5/6
85.19% Lines 23/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 841x   1x 1x 1x 1x                         1x 1x 1x   1x   1x 1x 1x       1x 1x       1x 1x             1x                           1x 1x             1x       1x         1x     1x            
import "../../../configEnv";
import { IUserService } from "@schemas/services/user/user.v1.service";
import Knex from "knex";
import knexfile from "@services/user/knexfile";
import { loadModels } from "@lib/objection-utils/objection-utils.lib";
import path from "path";
import {
  CreateReq,
  CreateRsp,
  FindReq,
  FindRsp,
  GetReq,
  GetRsp,
  RemoveReq,
  RemoveRsp,
  UpdateReq,
  UpdateRsp,
} from "@schemas/services/user/user.v1.schemas";
import User from "./models/user.model";
import _ from "lodash";
import { BadRequestError } from "@mod/errors/base-errors";
 
export default class UserService implements IUserService {
  async init(): Promise<void> {
    const masterKnex = Knex(knexfile.production);
    const slaveKnex = Knex(knexfile.slave);
    loadModels(masterKnex, slaveKnex, path.join(__dirname, "models"));
  }
 
  async Create(ctx, req: CreateReq): Promise<CreateRsp> {
    const user = await User.queryOnMaster().insert({});
    return user as any;
  }
 
  async Get(ctx, req: GetReq): Promise<GetRsp> {
    const { userId } = req;
    const user = await User.queryOnMaster()
      .where({
        id: userId,
      })
      .select("*")
      .limit(1)
      .first();
    return user as any;
  }
 
  async Remove(ctx, req: RemoveReq): Promise<RemoveRsp> {
    const { userId } = req;
    await User.queryOnMaster()
      .where({
        id: userId,
      })
      .delete();
    return {};
  }
 
  async Update(ctx, req: UpdateReq): Promise<UpdateRsp> {
    const { userId } = req;
    await User.queryOnMaster()
      .where({
        id: userId,
      })
      .patch({
        ..._.omit(req as any, ["userId"]),
      });
    return {};
  }
 
  async Find(ctx, req: FindReq): Promise<FindRsp> {
    Iif (Object.keys(req).length <= 0) {
      throw new BadRequestError({
        message: "at least 1 search param is required",
      });
    }
    const users = await User.query()
      .select("*")
      .where(req);
    return {
      list: users as any,
      total: users.length,
    };
  }
}