All files / src/transactions transactionService.ts

100% Statements 71/71
100% Branches 13/13
100% Functions 17/17
100% Lines 63/63

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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 1608x 8x               8x 8x       8x 8x             8x     8x       42x 42x 42x 42x 42x 42x   42x   42x                   42x     2x 2x 2x 2x 2x 2x     2x             2x           1x 1x   1x   1x         1x 1x     42x 2x 2x 2x 2x 2x 1x   1x 1x       42x 3x 3x 2x   1x     42x     3x 3x     3x 3x 3x 3x 2x     2x     2x 2x   1x       2x                               42x 6x 6x           42x 2x      
import { Injectable } from '@nestjs/common';
import gql from 'graphql-tag';
import {
  TransactionQueryInput,
  Transaction,
  TransactionConnection,
  EntityUuidGsiKeySchema,
  TransactionRequestInput,
} from '../types.d';
import { TransactionDb } from './transactionDb';
import {
  convertDbItemToTransaction,
  convertDbStreamToTransaction,
} from './transactionUtils';
import { DeviceVerification, DeviceService } from '../devices';
import {
  AppSyncClient,
  EnvironmentService,
  DynamodbService,
  LambdaService,
} from '../common_services';
import { TransactionRequest } from './transactionDto';
import { UpdateEventPublisher } from '../common_interfaces';
 
@Injectable()
export class TransactionService extends UpdateEventPublisher {
  transactionDb: TransactionDb;
 
  constructor(
    private readonly dynamodbService: DynamodbService,
    private readonly envService: EnvironmentService,
    private readonly deviceVerify: DeviceVerification,
    private readonly deviceService: DeviceService,
    private readonly appsyncClient: AppSyncClient,
    private readonly lambdaService: LambdaService,
  ) {
    super(appsyncClient, (deviceUuid) => this.deviceService.getDeviceStatus(deviceUuid));
 
    this.transactionDb = new TransactionDb(
      this.envService.deviceTableName,
      this.dynamodbService,
      envService.transactionGsi,
      envService.accessTokenGsi,
      envService.entityUuidGsi,
      envService.siteUuidGsi,
    );
  }
 
  requestTransaction = async (
    accessToken: string,
    event: TransactionRequestInput,
  ): Promise<{ status: boolean }> => {
    console.log(event);
    const cqrsCommandHandler = this.envService.cqrsCommandHandler;
    console.log('send transaction request to ', cqrsCommandHandler);
    try {
      const userIdentityId = await this.deviceService.getEntityUuidByAccessToken(
        accessToken,
      );
      const transactionRequest: TransactionRequest = {
        transactionId: event.id,
        catid: event.catid,
        caid: event.caid,
        iso8583: event.iso8583,
        userIdentityId,
      };
      const output = await this.lambdaService.lambda
        .invoke({
          FunctionName: cqrsCommandHandler,
          Payload: JSON.stringify(transactionRequest),
        })
        .promise();
      console.log('invoke command handler lambda response:', output);
      return { status: true };
    } catch (err) {
      console.error(err);
    }
    return { status: false };
  };
 
  subscribeTransactionResponse(event: any): any {
    // TODO - implement me - subscribe transaction response handler
    console.log(event);
    return { id: event.args.id };
  }
 
  processProjectionTransactionEvent = async (event: { payload: Transaction }) => {
    console.log(event);
    try {
      const { id, deviceUuid } = event.payload;
      const type = `transaction.${new Date().getTime()}`
      await this.transactionDb.saveTransaction(deviceUuid, id, type, event.payload)
      console.log(`Created Transaction: ${event.payload.id}`)
    } catch (e) {
      console.error(e)
      throw e
    }
  }
 
  getTransaction = async (transactionUuid: string): Promise<Transaction> => {
    const output = await this.transactionDb.getTransaction(transactionUuid);
    if (output.Items && output.Items.length > 0) {
      return convertDbItemToTransaction(output.Items[0]);
    }
    throw new Error(`Transaction ${transactionUuid} not found.`);
  };
 
  getTransactions = async (
    event: TransactionQueryInput,
    accessToken: string,
  ): Promise<TransactionConnection> => {
    const entityUuid = await this.deviceService.getEntityUuidByAccessToken(
      accessToken,
    );
    console.log('get entity uuid:', entityUuid);
    const output = await this.transactionDb.getTransactions(event, entityUuid);
    if (output && output.Items && output.Items.length > 0) {
      const transactions = output.Items.map<Transaction>((item) => convertDbItemToTransaction(item));
      const nextToken = output.LastEvaluatedKey
        ? (output.LastEvaluatedKey as EntityUuidGsiKeySchema)
        : undefined;
      const response = nextToken
        ? { transactions, nextToken }
        : { transactions };
      console.log('response:', response);
      return response;
    }
    return { transactions: [] };
  };
 
  prepareUpdateEventRequest(item: any, keys: any) {
    return {
      mutation: gql`
        mutation publishTransactionUpdateEvent(
          $item: TransactionInput!
        ) {
          publishTransactionUpdateEvent(transaction: $item) {
            ${keys}
          }
        }
      `,
      variables: {
        item,
      },
    };
  }
 
  onTransactionStream = async (event: any): Promise<void> => {
    console.info('transaction update event:', JSON.stringify(event));
    await this.publishUpdateEventToSubscribers<Transaction>(
      event,
      convertDbStreamToTransaction,
    );
  };
 
  onTransactionUpdate = async (accessToken: string): Promise<void> => {
    await this.deviceVerify.checkAccessToken(accessToken);
  };
}