All files / libs/lti/core/src/lib/use-cases/lib-custody custody.client.ts

0% Statements 0/51
0% Branches 0/1
0% Functions 0/1
0% Lines 0/51

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                                                                                                       
import { HttpException, HttpStatus, NotFoundException } from '@nestjs/common';
import axios, { type AxiosInstance } from 'axios';

import { assert, toError } from '@amalia/ext/typescript';
import { type LtiCustodyPortfolioRead } from '@amalia/lti/types';

import { configuration } from '../../configs';

const CUSTODY_BANK_ID = 1;

type GetCustomerPortfolioResponse = {
  totalCount: number;
  payload: LtiCustodyPortfolioRead[];
};

export class CustodyClient {
  private readonly client: AxiosInstance;

  public constructor() {
    this.client = this.getClient();
  }

  private getClient(): AxiosInstance {
    const { custodyApiKey, custodyApiUrl } = configuration.allShares;
    assert(custodyApiKey, new NotFoundException('Custody API key not found - cannot get custody.'));
    assert(custodyApiUrl, new NotFoundException('Custody API URL not found - cannot get custody.'));

    const axiosInstance = axios.create({
      baseURL: `${custodyApiUrl}/api/v1/custody-bank/${CUSTODY_BANK_ID}`,
      headers: {
        'x-api-key': custodyApiKey,
      },
      timeout: 10_000,
    });
    return axiosInstance;
  }

  public async getCustomerPortfolio(bankCustomerId: string) {
    try {
      const { data } = await this.client.get<GetCustomerPortfolioResponse>(
        `/portfolio?bankCustomerId=${bankCustomerId}`,
      );
      return data;
    } catch (err) {
      throw new HttpException(
        `Issue while getting data from custody service: ${toError(err).message}`,
        HttpStatus.BAD_GATEWAY,
      );
    }
  }
}