-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.js
More file actions
56 lines (50 loc) · 1.36 KB
/
validate.js
File metadata and controls
56 lines (50 loc) · 1.36 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
/**
* Validates if the given response is a valid CCXF object.
*
* CCXF (Clickswave Common Exchange Format) requires the response to follow:
* {
* status: number (HTTP status code),
* message: string,
* errors: array,
* data: object
* }
*
* Rules:
* 1. All fields must exist with correct types.
* 2. `errors` must always be an array.
* 3. If `status >= 400`, `errors` must contain at least one entry.
*
* @param {object} response - The API response to validate.
* @returns {boolean} - True if valid, otherwise false.
*/
export const validateCCXF = (response) => {
if (typeof response !== "object" || response === null) {
return false;
}
// Required keys and their expected types
const types = {
status: "number",
message: "string",
errors: "object",
data: "object"
};
// Check existence and type correctness
for (const key of Object.keys(types)) {
if (!(key in response)) return false;
const expectedType = types[key];
const actualType = typeof response[key];
// Special case for errors array
if (key === "errors") {
if (!Array.isArray(response.errors)) {
return false;
}
} else if (actualType !== expectedType || response[key] === null) {
return false;
}
}
// If status >= 400, errors must have at least one item
if (response.status >= 400 && response.errors.length === 0) {
return false;
}
return true;
};