-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRetry.ts
More file actions
136 lines (113 loc) · 5.44 KB
/
Retry.ts
File metadata and controls
136 lines (113 loc) · 5.44 KB
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
import { APIResponse, expect } from "@playwright/test";
import { config } from "../../config/env";
import { fetchApiResponse, findMatchingObject, validateFields } from "../apiHelper";
import { ApiResponse } from "../core/types";
const NHS_NUMBER_KEY = config.nhsNumberKey;
const NHS_NUMBER_KEY_EXCEPTION_DEMOGRAPHIC = config.nhsNumberKeyExceptionDemographic;
export async function validateApiResponse(validationJson: any, request: any): Promise<{ status: boolean; errorTrace?: any }> {
let status = false;
let endpoint = "";
let errorTrace: any = undefined;
try {
for (const apiValidation of validationJson) {
endpoint = apiValidation.validations.apiEndpoint;
var response = await pollAPI(endpoint, apiValidation, request);
console.info(response);
switch(response.status()) {
case 204:
console.info("now handling no content response");
const expectedCount = apiValidation.validations.expectedCount;
status = await HandleNoContentResponse(expectedCount, apiValidation, endpoint);
break;
case 200:
console.info("now handling OK response");
status = await handleOKResponse(apiValidation, endpoint, response);
default:
console.error("there was an error when handling response from ");
break;
}
}
}
catch (error) {
const errorMsg = `Endpoint: ${endpoint}, Error: ${error instanceof Error ? error.stack || error.message : error}`;
errorTrace = errorMsg;
console.error(errorMsg);
}
return { status, errorTrace };
}
async function handleOKResponse(apiValidation: any, endpoint: string, response: any ) : Promise<boolean>{
const responseBody = await response.json();
expect(Array.isArray(responseBody)).toBeTruthy();
const { matchingObject, nhsNumber, matchingObjects } = await findMatchingObject(endpoint, responseBody, apiValidation);
console.info(`Validating fields using 🅰️\t🅿️\tℹ️\t ${endpoint}`);
console.info(`From Response ${JSON.stringify(matchingObject, null, 2)}`);
return await validateFields(apiValidation, matchingObject, nhsNumber, matchingObjects);
}
async function HandleNoContentResponse(expectedCount: number, apiValidation: any, endpoint: string): Promise<boolean> {
if (expectedCount !== undefined && Number(expectedCount) === 0) {
console.info(`✅ Status 204: Expected 0 records for endpoint ${endpoint}`);
// Get NHS number for validation
const nhsNumber = apiValidation.validations.NHSNumber ||
apiValidation.validations.NhsNumber ||
apiValidation.validations[NHS_NUMBER_KEY] ||
apiValidation.validations[NHS_NUMBER_KEY_EXCEPTION_DEMOGRAPHIC];
console.info(`Validating fields using 🅰️\t🅿️\tℹ️\t ${endpoint}`);
console.info(`From Response: null (204 No Content - 0 records as expected)`);
return await validateFields(apiValidation, null, nhsNumber, []);
} else {
// 204 is unexpected, throw error to trigger retry
throw new Error(`Status 204: No data found in the table using endpoint ${endpoint}`);
}
}
async function pollAPI(endpoint: string, apiValidation: any, request: any): Promise<APIResponse> {
let apiResponse: APIResponse | null = null;
let i = 0;
let maxNumberOfRetries = config.maxNumberOfRetries;
let maxTimeBetweenRequests = config.maxTimeBetweenRequests;
console.info(`now trying request for ${maxNumberOfRetries} retries`);
while (i < maxNumberOfRetries) {
try {
apiResponse = await fetchApiResponse(endpoint, request);
if (apiResponse.status() == 200) {
console.info("200 response found")
break;
}
}
catch(exception) {
console.error("Error reading request body:", exception);
}
i++;
console.info(`http response completed ${i}/${maxNumberOfRetries} of number of reties`);
await new Promise(res => setTimeout(res, maxTimeBetweenRequests));
}
if (!apiResponse) {
throw new Error("apiResponse was never assigned");
}
return apiResponse;
}
export async function pollApiForOKResponse(httpRequest: () => Promise<ApiResponse>): Promise<ApiResponse>{
let apiResponse: ApiResponse | null = null;
let i = 0;
let maxNumberOfRetries = config.maxNumberOfRetries;
let maxTimeBetweenRequests = config.maxTimeBetweenRequests;
console.info(`now trying request for ${maxNumberOfRetries} retries`);
while (i < maxNumberOfRetries) {
try {
apiResponse = await httpRequest();
if (apiResponse.status == 200) {
console.info("200 response found")
break;
}
}
catch(exception) {
console.error("Error reading request body:", exception);
}
i++;
console.info(`http response completed ${i}/${maxNumberOfRetries} of number of reties`);
await new Promise(res => setTimeout(res, maxTimeBetweenRequests));
}
if (!apiResponse) {
throw new Error("apiResponse was never assigned");
}
return apiResponse;
};