Skip to content

Commit

Permalink
feat(cb2-10047): add service for aws SNS (#93)
Browse files Browse the repository at this point in the history
Co-authored-by: owen <[email protected]>
  • Loading branch information
shivangidas and owen authored Jan 22, 2024
1 parent a3dc937 commit 3bba0de
Show file tree
Hide file tree
Showing 12 changed files with 688 additions and 187 deletions.
4 changes: 2 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
},
"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
"source.fixAll": false,
"source.fixAll.eslint": true
"source.fixAll": "never",
"source.fixAll.eslint": "explicit"
},
}
795 changes: 637 additions & 158 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"dependencies": {
"@aws-sdk/client-dynamodb": "^3.341.0",
"@aws-sdk/client-lambda": "^3.362.0",
"@aws-sdk/client-sns": "^3.485.0",
"@aws-sdk/client-sqs": "^3.382.0",
"@aws-sdk/lib-dynamodb": "^3.341.0",
"@aws-sdk/util-dynamodb": "^3.362.0",
Expand Down
10 changes: 0 additions & 10 deletions src/handler/update-test-vrm.ts

This file was deleted.

9 changes: 8 additions & 1 deletion src/handler/updateVrm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import 'dotenv/config';

import { TechRecordType } from '@dvsa/cvs-type-definitions/types/v3/tech-record/tech-record-verb';
import { UpdateVrmRequestBody } from '../models/updateVrm';
import { SNSMessageBody, UpdateVrmRequestBody } from '../models/updateVrm';
import { processCherishedTransfer } from '../processors/processCherishedTransfer';
import { processCorrectVrm } from '../processors/processCorrectVrm';
import {
Expand All @@ -16,6 +16,7 @@ import { addHttpHeaders } from '../util/httpHeaders';
import logger from '../util/logger';
import { validateUpdateVrmRequest, validateVrm, validateVrmExists } from '../validators/update';
import { formatErrorMessage } from '../util/errorMessage';
import { publish } from '../services/sns';

export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
try {
Expand Down Expand Up @@ -67,6 +68,12 @@ export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayPr

await updateVehicle(recordsToArchive, recordsToUpdate);

const recordsToSend: SNSMessageBody[] = [];

recordsToUpdate.forEach((record) => recordsToSend.push({ ...record, userEmail: userDetails.email }));

await publish(JSON.stringify(recordsToSend), process.env.VRM_TRANSFERRED_ARN ?? '');

return addHttpHeaders({
statusCode: 200,
body: JSON.stringify(recordsToUpdate[0]),
Expand Down
4 changes: 4 additions & 0 deletions src/models/updateVrm.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { TechRecordType } from '@dvsa/cvs-type-definitions/types/v3/tech-record/tech-record-verb';

export type UpdateVrmRequestBody = {
newVrm: string
isCherishedTransfer: boolean,
thirdMark?: string
};

export type SNSMessageBody = TechRecordType<'get'> & { userEmail?: string };
26 changes: 26 additions & 0 deletions src/services/sns.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { SNSClient, PublishCommand } from '@aws-sdk/client-sns';
import logger from '../util/logger';

const snsClient = new SNSClient({ region: process.env.DYNAMO_AWS_REGION });

export const publish = async (message: string, topicArn: string) => {
logger.info('Sending SNS notification');

if (process.env.AWS_SAM_LOCAL) {
return '123';
}
const input = {
TopicArn: topicArn,
Message: message,
};

const command = new PublishCommand(input);
try {
const response = await snsClient.send(command);
logger.debug(response);
return undefined;
} catch (err: unknown) {
logger.error(err);
throw new Error(err as string);
}
};
2 changes: 1 addition & 1 deletion src/util/enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export enum ERRORS {
FAILED_UPDATE_MESSAGE = 'Failed to update record',
}
export enum ReasonForCreation {
EU_VEHICLE_CATEGORY_UPDATE = 'EU Vehicle Catergory updated.',
EU_VEHICLE_CATEGORY_UPDATE = 'EU Vehicle Category updated.',
RECORD_PROMOTED = 'Record promoted to current.',
}

Expand Down
13 changes: 0 additions & 13 deletions template.yml
Original file line number Diff line number Diff line change
Expand Up @@ -153,18 +153,5 @@ Resources:
Properties:
Path: !GetAtt LocalQueue.Arn
BatchSize: 10
UpdateTestVRMFunction:
Type: 'AWS::Serverless::Function'
Properties:
CodeUri: src/handler/
Handler: update-test-vrm.handler
Runtime: nodejs18.x
Timeout: 20
Events:
SQSEvent:
Type: SQS
Properties:
Path: !GetAtt LocalQueue.Arn
BatchSize: 10
LocalQueue:
Type: AWS::SQS::Queue
7 changes: 7 additions & 0 deletions tests/unit/handler/updateVrm.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const mockDonorVehicle = jest.fn();
const mockValidateVrmExists = jest.fn();
const mockValidateUpdateVrmRequest = jest.fn();
const mockValidateVrm = jest.fn();
const mockPublish = jest.fn();

import { APIGatewayProxyEvent } from 'aws-lambda';
import { handler } from '../../../src/handler/updateVrm';
Expand All @@ -28,6 +29,10 @@ jest.mock('../../../src/services/donorVehicle', () => ({
donorVehicle: mockDonorVehicle,
}));

jest.mock('../../../src/services/sns', () => ({
publish: mockPublish,
}));

jest.mock('../../../src/validators/update', () => ({
validateVrmExists: mockValidateVrmExists,
validateUpdateVrmRequest: mockValidateUpdateVrmRequest,
Expand Down Expand Up @@ -73,9 +78,11 @@ describe('update vrm handler', () => {
mockValidateVrmExists.mockReturnValueOnce(false);
mockDonorVehicle.mockReturnValue([{ ...carData, primaryVrm: 'DONORVRM' }, undefined]);
mockUpdateVehicle.mockResolvedValueOnce({});
mockPublish.mockResolvedValueOnce(undefined);
const result = await handler(request);

expect(mockGetBySystemNumberAndCreatedTimestamp).toHaveBeenCalledTimes(1);
expect(mockPublish).toHaveBeenCalledTimes(1);
expect(result.statusCode).toBe(200);
expect(result.body).not.toBeNull();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ describe('syncTestResultInfo', () => {
expect(mockGetBySystemNumberAndCreatedTimestamp).toHaveBeenCalledTimes(2);
expect(mockUpdateVehicle).toHaveBeenCalledTimes(1);
});
it('should not call update if record is current and EuVehicleCatergory is not updated', async () => {
it('should not call update if record is current and EuVehicleCategory is not updated', async () => {
mockSearchByCriteria.mockResolvedValueOnce([{ techRecord_statusCode: 'current' }]);
mockGetBySystemNumberAndCreatedTimestamp.mockResolvedValueOnce(hgvData[1]);
await syncTestResultInfo('5000', 'submitted', 'pass', '47', '012345', 'Test User', undefined);
Expand Down
2 changes: 1 addition & 1 deletion webpack/webpack.production.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const AwsSamPlugin = require("aws-sam-webpack-plugin");


const LAMBDA_NAMES = ['SearchLambdaFunction', 'GetLambdaFunction', 'PostLambdaFunction', 'PatchLambdaFunction',
'ArchiveLambdaFunction', 'UnarchiveLambdaFunction', 'PromoteLambdaFunction', 'UpdateVrmFunction', 'UpdateVinFunction', 'GeneratePlateFunction', 'GenerateLetterFunction', 'SyncTestResultInfoFunction', 'UpdateTestVRMFunction'];
'ArchiveLambdaFunction', 'UnarchiveLambdaFunction', 'PromoteLambdaFunction', 'UpdateVrmFunction', 'UpdateVinFunction', 'GeneratePlateFunction', 'GenerateLetterFunction', 'SyncTestResultInfoFunction'];
const OUTPUT_FOLDER = './'
const REPO_NAME = 'cvs-svc-technical-records-v3';
const BRANCH_NAME = branchName().replace(/\//g, "-");
Expand Down

0 comments on commit 3bba0de

Please sign in to comment.