All files / src/service TargetsDataSourceService.ts

100% Statements 41/41
87.5% Branches 28/32
100% Functions 7/7
100% Lines 39/39

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  11x 11x   11x 11x   11x   11x         17x 17x   17x 17x         3x 3x             3x 3x 3x 3x           5x           5x   5x       2x 2x                   2x 2x   1x       1x           1x       1x   1x                     1x         3x 3x 1x             2x 2x                   2x 2x   1x       1x           1x        
 
import { DeleteItemCommand, DynamoDBClient, GetItemCommand, PutItemCommand, ScanCommand } from "@aws-sdk/client-dynamodb"; // ES Modules 
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';
import { FlowTarget, Logger, LoggerFactory, PaginatedResults } from 'shared_types';
import { AppConfiguration } from 'src/common/configuration/AppConfiguration';
import RuleConfigError from "src/common/RuleConfigError";
import { FlowTargetInput } from "src/types/FlowTarget";
import { inject, injectable } from 'tsyringe';
@injectable()
export class TargetsDataSourceService {
 
    logger: Logger;
    targetTableName: string;
    constructor(@inject('LoggerFactory') loggerFactory: LoggerFactory,
        @inject('DynamoDBClient') private dynamoDBClient: DynamoDBClient,
        @inject('AppConfiguration') private appConfiguration: AppConfiguration,
    ) {
        this.logger = loggerFactory.getLogger('ObjectsDataSourceService');
        this.targetTableName = this.appConfiguration.getDefinitionSourceFor('TARGET')?.tableName ?? '';
 
    }
 
    public async getTargets(limit?: number, nextToken?: string): Promise<PaginatedResults<FlowTarget>> {
        this.logger.info(`Scanning table ${this.targetTableName} with ${limit} and nextToken ${nextToken}`);
        const scanTableCommand: ScanCommand = new ScanCommand(
            {
                TableName: this.targetTableName,
                ...(limit && { Limit: limit }),
                ...(nextToken && { ExclusiveStartKey: marshall({ id: nextToken }) })
            }
        );
        const response = await this.dynamoDBClient.send(scanTableCommand);
        const lastEvaluatedKey = response.LastEvaluatedKey?.id ? unmarshall(response.LastEvaluatedKey) : undefined;
        return {
            results: response.Items?.map(i => unmarshall(i) as FlowTarget) ?? [],
            ...(lastEvaluatedKey && { nextToken: lastEvaluatedKey['id'] })
        };
    }
 
    public async getTargetBy(id: string): Promise<FlowTarget | undefined> {
        const getItemCommand: GetItemCommand = new GetItemCommand(
            {
                Key: marshall({ id: id }),
                TableName: this.targetTableName
            }
        );
        const { Item: item } = await this.dynamoDBClient.send(getItemCommand);
 
        return item ? unmarshall(item) as FlowTarget : undefined;
    }
 
    public async createTarget(targetInput: FlowTargetInput, operatorIdentity: string): Promise<FlowTarget> {
        const input: FlowTarget = { ...targetInput, createdBy: operatorIdentity, lastUpdated: new Date().toISOString() };
        const getItemCommand: PutItemCommand = new PutItemCommand(
            {
                Item: marshall(input),
                TableName: this.targetTableName,
                ConditionExpression: "attribute_not_exists(#id)",
                ExpressionAttributeNames: {
                    "#id": "id",
                },
            }
        );
        try {
            await this.dynamoDBClient.send(getItemCommand);
        } catch (error) {
            this.logger.error(
                'Error occurred when inserting a new target into database ',
                error
            );
            throw new RuleConfigError(
                'An error occurred when saving the new target',
                500,
                true
            );
        }
        return input;
    }
 
    public async deleteObject(id: string): Promise<void> {
        this.logger.info(`attempt to delete the object ${id}`);
       
        const deleteItemCmd: DeleteItemCommand = new DeleteItemCommand(
            {
                Key: marshall({ id: id }),
                TableName: this.targetTableName,
                ConditionExpression: "attribute_exists(#id)",
                ExpressionAttributeNames: {
                    "#id": "id",
                }
            }
        );
 
        await this.dynamoDBClient.send(deleteItemCmd);
       
    }
 
    public async updateObject(target: FlowTargetInput): Promise<FlowTarget> {
        const currentTarget = await this.getTargetBy(target.id);
        if (!currentTarget) {
            throw new RuleConfigError(
                `Requested target not exists ${target.id}`,
                404,
                true
            );
        }
 
        const input: FlowTarget = { ...currentTarget, type: target.type, value: target.value, description: target.description, lastUpdated: new Date().toISOString() };
        const getItemCommand: PutItemCommand = new PutItemCommand(
            {
                Item: marshall(input),
                TableName: this.targetTableName,
                ConditionExpression: "attribute_exists(#id)",
                ExpressionAttributeNames: {
                    "#id": "id",
                },
            }
        );
        try {
            await this.dynamoDBClient.send(getItemCommand);
        } catch (error) {
            this.logger.error(
                'Error occurred when updating a new target into database ',
                error
            );
            throw new RuleConfigError(
                'An error occurred when saving the new target',
                500,
                true
            );
        }
        return input;
    }
}