Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.0 kB
2
Indexable
Never
import * as E from "fp-ts/Either";
import { pipe } from "fp-ts/lib/function";
import * as TE from "fp-ts/TaskEither";

import {
  saveResponseError,
  SaveResponseError,
  SaveResponseSuccess,
  successfulSaveResponse,
} from "@lambdas/kyc/singpass/types";

import Database from "../database";
import { InfrastructureError } from "../errors";
import { SingpassKycResponse } from "../models";
import { databaseSaveRecordError, DatabaseSaveRecordError } from "../types";
import { SingpassKycDbModel } from "./models/SingpassKycDbModel";
import { EntityManager } from "typeorm";

export class SingpassKycRepository {
  constructor(private database: Database) {}

  public create(
    singpassKycResponse: SingpassKycResponse,
    entityManager: EntityManager
  ): TE.TaskEither<
    DatabaseSaveRecordError | InfrastructureError,
    void
  > {
    return pipe(
      TE.tryCatch(
        () => entityManager.insert(SingpassKycDbModel, singpassKycResponse),
        (err) => databaseSaveRecordError(E.toError(err))
      ),
      TE.map(() => undefined)
    );
  }

  private readSingpassKycResponse(
    record: SingpassKycDbModel
  ): Pick<
    SingpassKycResponse,
    | "userId"
    | "uinfin"
    | "name"
    | "sex"
    | "dob"
    | "nationality"
    | "email"
    | "regadd"
  > {
    return {
      userId: record.userId,
      uinfin: record.uinfin,
      name: record.name!,
      sex: record.sex!,
      dob: record.dob!,
      nationality: record.nationality!,
      email: record.email!,
      regadd: record.regadd!,
    };
  }

  public safeCreate(
    singpassKycResponse: SingpassKycResponse,
    entityManager: EntityManager
  ): TE.TaskEither<SaveResponseError, SaveResponseSuccess> {
    return pipe(
      TE.tryCatch(
        () => this.create(singpassKycResponse, entityManager)(),
        (err) =>
          saveResponseError(singpassKycResponse, E.toError(JSON.stringify(err)))
      ),
      TE.map(() => successfulSaveResponse())
    );
  }
}