All files / service RulesDataSourceService.ts

98.33% Statements 59/60
86.21% Branches 50/58
90.91% Functions 10/11
100% Lines 57/57

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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 2036x 6x   6x 6x   6x 6x   6x       15x 15x   15x 15x           1x 1x                       1x 1x 1x 1x       3x 3x                               3x   3x   3x 3x   3x 3x 3x           2x           2x   2x         3x 3x             3x 3x 3x 3x         2x                           2x 2x     1x       1x           1x       2x 2x                   2x 2x   1x       1x           1x       2x 2x 2x 2x                                   2x 2x   1x       1x           1x        
import { DeleteItemCommand, DynamoDBClient, GetItemCommand, PutItemCommand, QueryCommand, QueryCommandInput, ScanCommand, ScanCommandInput } from "@aws-sdk/client-dynamodb"; // ES Modules 
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';
import { FlowRule, Logger, LoggerFactory, PaginatedResults } from 'shared_types';
import { AppConfiguration } from 'src/common/configuration/AppConfiguration';
import RuleConfigError from "src/common/RuleConfigError";
import { CreateFlowRuleInput } from "src/types/FlowRule";
import { inject, injectable } from 'tsyringe';
import { v4 as uuidv4 } from 'uuid';
@injectable()
export class RulesDataSourceService {
    logger: Logger;
    ruleTableName: string;
    constructor(@inject('LoggerFactory') loggerFactory: LoggerFactory,
        @inject('DynamoDBClient') private dynamoDBClient: DynamoDBClient,
        @inject('AppConfiguration') private appConfiguration: AppConfiguration,
    ) {
        this.logger = loggerFactory.getLogger('RuleDataSourceService');
        this.ruleTableName = this.appConfiguration.getDefinitionSourceFor('RULE')?.tableName ?? '';
 
    }
 
    public async getRuleByReferences(objectId: string):Promise<FlowRule[]> {
        //scan table for reference, return only limit=50 tops rules
        this.logger.info(`Query table ${this.ruleTableName} `);
        const input: ScanCommandInput = {
            TableName: this.ruleTableName,
            ExpressionAttributeValues: marshall({
                ":source": objectId,
                ":destination": objectId,
            }),
            ExpressionAttributeNames: {
                '#source': 'source',
                '#destination': 'destination'
            },
            FilterExpression: "#source = :source or #destination =:destination",
        };
        const cmd = new ScanCommand(input);
        const response = await this.dynamoDBClient.send(cmd);
        this.logger.info('getRuleByReferences response', response);
       return response.Items?.map(i => unmarshall(i) as FlowRule) ?? []
    }
 
    public async getRulesByGroupId(ruleGroupId: string, limit?: number, nextToken?: string): Promise<PaginatedResults<FlowRule>> {
        this.logger.info(`Query table ${this.ruleTableName} with ${limit} and nextToken ${nextToken} , rulegroupId ${ruleGroupId}`);
        const input: QueryCommandInput = {
            TableName: this.ruleTableName,
            IndexName: 'ruleGroupId',
            KeyConditionExpression: "#ruleGroupId = :ruleGroupId",
            ExpressionAttributeValues: marshall({
                ":ruleGroupId": ruleGroupId,
                ":status": 'DELETED',
            }),
            ExpressionAttributeNames: {
                '#ruleGroupId': 'ruleGroupId',
                '#status': 'status'
            },
            FilterExpression: "#status <> :status",
            ...(limit && { Limit: limit }),
            ...(nextToken && { ExclusiveStartKey: marshall({ id: nextToken, ruleGroupId: ruleGroupId }) }),
        };
        const command = new QueryCommand(input);
 
        this.logger.info('sending query command to ddb', input);
 
        const response = await this.dynamoDBClient.send(command);
        this.logger.info('dynamoDBClient object', response);
 
        const lastEvaluatedKey = response.LastEvaluatedKey?.id ? unmarshall(response.LastEvaluatedKey) : undefined;
        return {
            results: response.Items?.map(i => unmarshall(i) as FlowRule) ?? [],
            ...(lastEvaluatedKey && { nextToken: lastEvaluatedKey['id'] })
        };
    }
 
    public async getRuleBy(id: string): Promise<FlowRule | undefined> {
        const getItemCommand: GetItemCommand = new GetItemCommand(
            {
                Key: marshall({ id: id }),
                TableName: this.ruleTableName
            }
        );
        const { Item: item } = await this.dynamoDBClient.send(getItemCommand);
 
        return item ? unmarshall(item) as FlowRule : undefined;
    }
 
    public async getRules(limit?: number, nextToken?: string): Promise<PaginatedResults<FlowRule>> {
 
        this.logger.info(`Scaning table ${this.ruleTableName} with ${limit} and nextToken ${nextToken}`);
        const scanTableCommand: ScanCommand = new ScanCommand(
            {
                TableName: this.ruleTableName,
                ...(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 FlowRule) ?? [],
            ...(lastEvaluatedKey && { nextToken: lastEvaluatedKey['id'] })
        };
    }
    public async deleteRuleBy(ruleGroupId: string, ruleId: string): Promise<string> {
        const updateItemCommand: DeleteItemCommand = new DeleteItemCommand(
            {
                Key: marshall({ id: ruleId }),
                TableName: this.ruleTableName,
                ConditionExpression: "attribute_exists(#id) and #ruleGroupId = :ruleGroupId",
                ExpressionAttributeNames: {
                    "#id": "id",
                    "#ruleGroupId": "ruleGroupId",
                },
                ExpressionAttributeValues: marshall({
                    ":ruleGroupId": ruleGroupId
                })
            }
        );
        try {
            await this.dynamoDBClient.send(updateItemCommand);
 
        } catch (error) {
            this.logger.error(
                'An error occurred when deleting an existing rule',
                error
            );
            throw new RuleConfigError(
                'An error occurred when deleting an existing rule',
                500,
                true
            );
        }
        return ruleId;
    }
 
    public async createRule(requestedRule: CreateFlowRuleInput): Promise<FlowRule> {
        const input: FlowRule = { ...requestedRule, lastUpdated: new Date().toISOString(), id: uuidv4(), version: 0 };
        const getItemCommand: PutItemCommand = new PutItemCommand(
            {
                Item: marshall(input),
                TableName: this.ruleTableName,
                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 rule into database ',
                error
            );
            throw new RuleConfigError(
                'An error occurred when saving the new rule',
                500,
                true
            );
        }
        return input;
    }
 
    public async updateRule(requestedRule: FlowRule): Promise<FlowRule> {
        const input: FlowRule = { ...requestedRule, lastUpdated: new Date().toISOString() };
        const currentVersion = requestedRule.version;
        const newVersion = currentVersion + 1;
        const getItemCommand: PutItemCommand = new PutItemCommand(
            {
                Item: marshall({ ...input, version: newVersion }),
                TableName: this.ruleTableName,
                ConditionExpression: "attribute_exists(#id) and #ruleGroupId = :ruleGroupId and #version = :expectedVersion",
 
                ExpressionAttributeNames: {
                    "#id": "id",
                    "#ruleGroupId": "ruleGroupId",
                    '#version': 'version',
                },
                ExpressionAttributeValues: marshall({
                    ":ruleGroupId": requestedRule.ruleGroupId,
                    ':expectedVersion': currentVersion,
                })
 
            }
        );
        try {
            await this.dynamoDBClient.send(getItemCommand);
        } catch (error) {
            this.logger.error(
                'Error occurred when inserting a new rule into database ',
                error
            );
            throw new RuleConfigError(
                'An error occurred when saving the new rule',
                500,
                true
            );
        }
        return input;
    }
}