Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(cb2-11004): add await for promises #166

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"test": "npm run test:unit -- --coveragePathIgnorePatterns='<rootDir>/tests/' --coverage",
"test-i": "BRANCH=local jest --testMatch=\"**/*.intTest.ts\" --runInBand",
"lint": "tslint src/**/*.ts tests/**/*.ts -q",
"lint-fix": "tslint src/**/*.ts tests/**/*.ts -q --fix",
"lint:fix": "tslint src/**/*.ts tests/**/*.ts -q --fix",
"security-checks": "git secrets --scan",
"prepush": "npm run test && npm run build && npm run test-i",
"sonar-scanner": "npm run test && sonar-scanner",
Expand Down Expand Up @@ -106,4 +106,4 @@
"pre-push": "npm run prepush"
}
}
}
}
143 changes: 75 additions & 68 deletions src/services/CertificateGenerationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ class CertificateGenerationService {
public async generateCertificate(
testResult: any
): Promise<IGeneratedCertificateResponse> {
console.warn("this is the test result", JSON.stringify(testResult));
const config: IMOTConfig = this.config.getMOTConfig();
const iConfig: IInvokeConfig = this.config.getInvokeConfig();
const testType: any = testResult.testTypes;
Expand All @@ -77,6 +78,7 @@ class CertificateGenerationService {
const payload: string = JSON.stringify(
await this.generatePayload(testResult, shouldTranslateTestResult)
);
console.warn("this is the payload in generate cert", payload);

const certificateTypes: any = {
psv_pass: config.documentNames.vtp20,
Expand Down Expand Up @@ -138,6 +140,7 @@ class CertificateGenerationService {
.invoke(invokeParams)
.then(
async (response: InvocationResponse) => {
console.warn("validateInvocationResponse called in generateCertificate");
const documentPayload: any = await this.lambdaClient.validateInvocationResponse(response);
const resBody: string = documentPayload.body;
const responseBuffer: Buffer = Buffer.from(resBody, "base64");
Expand All @@ -164,7 +167,7 @@ class CertificateGenerationService {
}
)
.catch((error: ServiceException | Error) => {
console.log(error);
console.error("failed in generate certificate", error);
throw error;
});
}
Expand Down Expand Up @@ -262,8 +265,11 @@ class CertificateGenerationService {
while (retries < 3) {
try {
const response: InvocationResponse = await this.lambdaClient.invoke(invokeParams);
const payload: any = this.lambdaClient.validateInvocationResponse(response);
console.warn("validateInvocationResponse called in getTestStations count -", retries);
const payload: any = await this.lambdaClient.validateInvocationResponse(response);
console.log("getTestStations :", payload);
const testStationsParsed = JSON.parse(payload.body);
console.log("testStationsParsed :~", testStationsParsed);

if (!testStationsParsed || testStationsParsed.length === 0) {
throw new HTTPError(400, `${ERRORS.LAMBDA_INVOCATION_BAD_DATA} ${JSON.stringify(payload)}.`
Expand Down Expand Up @@ -797,76 +803,68 @@ class CertificateGenerationService {
},
})),
};
try {
const lambdaResponse = await this.lambdaClient.invoke(invokeParams);
console.log("getOdometerHistory lambdaResponse :", lambdaResponse);
console.warn("validateInvocationResponse called in getOdometerHistory");
const payload = await this.lambdaClient.validateInvocationResponse(lambdaResponse);
console.log("getOdometerHistory payload :", payload);
const testResults: any[] = JSON.parse(payload.body);
console.log("getOdometerHistory testResults :", testResults);

if (!testResults || testResults.length === 0) {
throw new HTTPError(
400,
`${ERRORS.LAMBDA_INVOCATION_BAD_DATA} ${JSON.stringify(payload)}.`
);
}
// Sort results by testEndTimestamp
testResults.sort((first: any, second: any): number => {
if (
moment(first.testEndTimestamp).isBefore(second.testEndTimestamp)
) {
return 1;
}
if (
moment(first.testEndTimestamp).isAfter(second.testEndTimestamp)
) {
return -1;
}
return 0;
});

return this.lambdaClient
.invoke(invokeParams)
.then(
(
response: InvocationResponse
) => {
const payload: any =
this.lambdaClient.validateInvocationResponse(response);
// TODO: convert to correct type
const testResults: any[] = JSON.parse(payload.body);

if (!testResults || testResults.length === 0) {
throw new HTTPError(
400,
`${ERRORS.LAMBDA_INVOCATION_BAD_DATA} ${JSON.stringify(payload)}.`
);
}
// Sort results by testEndTimestamp
testResults.sort((first: any, second: any): number => {
if (
moment(first.testEndTimestamp).isBefore(second.testEndTimestamp)
) {
return 1;
}

if (
moment(first.testEndTimestamp).isAfter(second.testEndTimestamp)
) {
return -1;
}

return 0;
});

// Remove the first result as it should be the current one.
testResults.shift();

// Set the array to only submitted tests (exclude cancelled)
const submittedTests = testResults.filter((testResult) => {
return testResult.testStatus === "submitted";
});
// Remove the first result as it should be the current one.
testResults.shift();

const filteredTestResults = submittedTests
.filter(({ testTypes }) =>
testTypes?.some(
(testType: ITestType) =>
testType.testTypeClassification ===
"Annual With Certificate" &&
(testType.testResult === "pass" ||
testType.testResult === "prs")
)
)
.slice(0, 3); // Only last three entries are used for the history.
// Set the array to only submitted tests (exclude cancelled)
const submittedTests = testResults.filter((testResult) => {
return testResult.testStatus === "submitted";
});

const filteredTestResults = submittedTests
.filter(({ testTypes }) =>
testTypes?.some(
(testType: ITestType) =>
testType.testTypeClassification ===
"Annual With Certificate" &&
(testType.testResult === "pass" ||
testType.testResult === "prs")
)
)
.slice(0, 3); // Only last three entries are used for the history.
return {
OdometerHistoryList: filteredTestResults.map((testResult) => {
return {
OdometerHistoryList: filteredTestResults.map((testResult) => {
return {
value: testResult.odometerReading,
unit: testResult.odometerReadingUnits,
date: moment(testResult.testEndTimestamp).format("DD.MM.YYYY"),
};
}),
value: testResult.odometerReading,
unit: testResult.odometerReadingUnits,
date: moment(testResult.testEndTimestamp).format("DD.MM.YYYY"),
};
}
)
.catch((error: ServiceException | Error) => {
console.log(error);
throw error;
});
}),
};
} catch (error) {
console.log(error);
throw error;
}
}

/**
Expand Down Expand Up @@ -906,6 +904,7 @@ class CertificateGenerationService {
};
try {
const lambdaResponse = await this.lambdaClient.invoke(invokeParams);
console.warn("validateInvocationResponse called in callSearchTechRecords");
const res = await this.lambdaClient.validateInvocationResponse(lambdaResponse);
return JSON.parse(res.body);
} catch (e) {
Expand Down Expand Up @@ -937,6 +936,7 @@ class CertificateGenerationService {
};
try {
const lambdaResponse = await this.lambdaClient.invoke(invokeParams);
console.warn("validateInvocationResponse called in callGetTechRecords");
const res = await this.lambdaClient.validateInvocationResponse(lambdaResponse);
return JSON.parse(res.body);
} catch (e) {
Expand Down Expand Up @@ -1035,13 +1035,20 @@ class CertificateGenerationService {
while (retries < 3) {
try {
const response: InvocationResponse = await this.lambdaClient.invoke(invokeParams);
const payload: any = this.lambdaClient.validateInvocationResponse(response);
console.warn("validateInvocationResponse called in getDefectTranslations");
const payload: any = await this.lambdaClient.validateInvocationResponse(response);
console.log("getDefectTranslations :", payload);

const defectsParsed = JSON.parse(payload.body);
console.log("defectsParsed :~", defectsParsed);


if (!defectsParsed || defectsParsed.length === 0) {
throw new HTTPError(400, `${ERRORS.LAMBDA_INVOCATION_BAD_DATA} ${JSON.stringify(payload)}.`);
}
defects = defectsParsed;
console.log("retries ~: ", retries);
console.log("defects ~: ", defects);
return defects;
} catch (error) {
retries++;
Expand Down
10 changes: 3 additions & 7 deletions src/services/LambdaService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,7 @@ class LambdaService {
public async invoke(
params: InvocationRequest
): Promise<InvocationResponse> {
try {
return await this.lambdaClient.send(new InvokeCommand(params));
} catch (err) {
throw err;
}
return await this.lambdaClient.send(new InvokeCommand(params));
}

/**
Expand All @@ -40,6 +36,7 @@ class LambdaService {
public validateInvocationResponse(
response: InvocationResponse
): Promise<any> {
// console.warn("payload", response.Payload);
if (
!response.Payload ||
Buffer.from(response.Payload).toString() === "" ||
Expand All @@ -50,9 +47,8 @@ class LambdaService {
`${ERRORS.LAMBDA_INVOCATION_ERROR} ${response.StatusCode} ${ERRORS.EMPTY_PAYLOAD}`
);
}

const payload: any = JSON.parse(Buffer.from(response.Payload).toString());

console.warn("parsed payload", payload);
if (payload.statusCode >= 400) {
throw new HTTPError(
500,
Expand Down
18 changes: 3 additions & 15 deletions src/services/S3BucketService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,7 @@ class S3BucketService {
Metadata: metadata,
});

try {
return await this.s3Client.send(command);
} catch (err) {
throw err;
}
return await this.s3Client.send(command);
}

/**
Expand All @@ -58,11 +54,7 @@ class S3BucketService {
Key: `${process.env.BRANCH}/${fileName}`,
});

try {
return this.s3Client.send(command);
} catch (err) {
throw err;
}
return this.s3Client.send(command);
}

/**
Expand All @@ -79,11 +71,7 @@ class S3BucketService {
Key: `${process.env.BRANCH}/${fileName}`,
});

try {
return this.s3Client.send(command);
} catch (err) {
throw err;
}
return this.s3Client.send(command);
}
}

Expand Down
Loading