All files / src/service ObjectsDataSourceService.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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163                              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      
/* 
  Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  
  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  
      http://www.apache.org/licenses/LICENSE-2.0
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
import {
    DeleteItemCommand,
    DynamoDBClient,
    GetItemCommand,
    PutItemCommand,
    ScanCommand,
} from '@aws-sdk/client-dynamodb'; // ES Modules
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';
import { FlowObject, Logger, LoggerFactory, PaginatedResults } from 'shared_types';
import { AppConfiguration } from 'src/common/configuration/AppConfiguration';
import RuleConfigError from 'src/common/RuleConfigError';
import { FlowObjectInput } from 'src/types/FlowTarget';
import { inject, injectable } from 'tsyringe';
@injectable()
export class ObjectsDataSourceService {
    logger: Logger;
    objectTableName: string;
    constructor(
        @inject('LoggerFactory') loggerFactory: LoggerFactory,
        @inject('DynamoDBClient') private dynamoDBClient: DynamoDBClient,
        @inject('AppConfiguration') private appConfiguration: AppConfiguration
    ) {
        this.logger = loggerFactory.getLogger('ObjectsDataSourceService');
        this.objectTableName =
            this.appConfiguration.getDefinitionSourceFor('OBJECT')?.tableName ?? '';
    }
 
    public async getObjects(
        limit?: number,
        nextToken?: string
    ): Promise<PaginatedResults<FlowObject>> {
        this.logger.info(
            `Scanning table ${this.objectTableName} with ${limit} and nextToken ${nextToken}`
        );
        const scanTableCommand: ScanCommand = new ScanCommand({
            TableName: this.objectTableName,
            ...(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 FlowObject) ?? [],
            ...(lastEvaluatedKey && { nextToken: lastEvaluatedKey['id'] }),
        };
    }
 
    public async getObjectBy(id: string): Promise<FlowObject | undefined> {
        const getItemCommand: GetItemCommand = new GetItemCommand({
            Key: marshall({ id: id }),
            TableName: this.objectTableName,
        });
        const { Item: item } = await this.dynamoDBClient.send(getItemCommand);
 
        return item ? (unmarshall(item) as FlowObject) : undefined;
    }
 
    public async createObject(
        targetInput: FlowObjectInput,
        operatorIdentity: string
    ): Promise<FlowObject> {
        const input: FlowObject = {
            ...targetInput,
            createdBy: operatorIdentity,
            lastUpdated: new Date().toISOString(),
        };
        const getItemCommand: PutItemCommand = new PutItemCommand({
            Item: marshall(input),
            TableName: this.objectTableName,
            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 object into database ',
                error
            );
            throw new RuleConfigError(
                'An error occurred when saving the new object',
                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.objectTableName,
            ConditionExpression: 'attribute_exists(#id)',
            ExpressionAttributeNames: {
                '#id': 'id',
            },
        });
 
        await this.dynamoDBClient.send(deleteItemCmd);
    }
 
    public async updateObject(ruleObject: FlowObjectInput): Promise<FlowObject> {
        const currentTarget = await this.getObjectBy(ruleObject.id);
        if (!currentTarget) {
            throw new RuleConfigError(
                `Requested object not exists ${ruleObject.id}`,
                404,
                true
            );
        }
 
        const input: FlowObject = {
            ...currentTarget,
            type: ruleObject.type,
            value: ruleObject.value,
            lastUpdated: new Date().toISOString(),
        };
        const getItemCommand: PutItemCommand = new PutItemCommand({
            Item: marshall(input),
            TableName: this.objectTableName,
            ConditionExpression: 'attribute_exists(#id)',
            ExpressionAttributeNames: {
                '#id': 'id',
            },
        });
        try {
            await this.dynamoDBClient.send(getItemCommand);
        } catch (error) {
            this.logger.error(
                'Error occurred when updating a new object into database ',
                error
            );
            throw new RuleConfigError(
                'An error occurred when saving the new object',
                500,
                true
            );
        }
        return input;
    }
}