All files / services/resume resume.service.ts

0% Statements 0/24
0% Branches 0/2
0% Functions 0/6
0% Lines 0/23

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                                                                                                                         
import "../../../configEnv";
import { IBSResumeService } from "@schemas/services/resume/resume.v1.service";
import Knex from "knex";
import knexfile from "@services/resume/knexfile";
import { loadModels } from "@lib/objection-utils/objection-utils.lib";
import path from "path";
import * as Schema from "@schemas/services/resume/resume.v1.schemas";
import { Context } from "@versed/context";
import Resume from "./models/resume.model";
import merge from "merge";
import { optimisticLockTransaction } from "@lib/transaction/transaction.lib";
 
export default class BSResumeService implements IBSResumeService {
  async init(): Promise<void> {
    const masterKnex = Knex(knexfile.production);
    const slaveKnex = Knex(knexfile.slave);
    loadModels(masterKnex, slaveKnex, path.join(__dirname, "models"));
  }
 
  async Get(ctx: Context, req: Schema.GetReq): Promise<Schema.GetRsp> {
    const resume = await Resume.query().findById(1);
    return resume.data;
  }
 
  async Replace(ctx: Context, req: Schema.ReplaceReq): Promise<Schema.ReplaceRsp> {
    await Resume.queryOnMaster()
      .where({
        id: 1,
      })
      .update({
        data: JSON.stringify(req),
        version: Resume.raw("version + 1"),
      });
    return {};
  }
 
  async Update(ctx: Context, req: Schema.UpdateReq): Promise<Schema.UpdateRsp> {
    // Update using optimistic lock transaction
    await optimisticLockTransaction(1, async lockFailure => {
      const resume = await this.Get(ctx, {});
 
      const newData = merge.recursive(true, resume.data, req);
 
      const affected = await Resume.queryOnMaster()
        .where({
          id: resume.id,
          version: resume.version,
        })
        .patch({
          version: resume.version + 1,
          data: JSON.stringify(newData),
        });
      if (affected === 0) {
        lockFailure();
      }
    });
 
    return {};
  }
}