-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapiUtil.ts
More file actions
76 lines (65 loc) · 2.8 KB
/
apiUtil.ts
File metadata and controls
76 lines (65 loc) · 2.8 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
import { RapLPCustomSpectral } from "./RapLPCustomSpectral.ts";
import { Document } from "@stoplight/spectral-core"
import Parsers from "@stoplight/spectral-parsers"
import { ERROR_TYPE, RapLPBaseApiError } from "./RapLPBaseApiErrorHandling.ts";
import yaml from "js-yaml"
export const validateYamlInput = (input: string): input is string => {
try {
const parsed = yaml.load(input); // Parsar YAML till ett JSON-objekt
if (typeof parsed !== 'object' || parsed === null) {
throw new RapLPBaseApiError(
"Could not validate Yaml",
"Parsed YAML is not a valid object",
ERROR_TYPE.BAD_REQUEST);
}
// Kontrollera att alla nödvändiga toppnivånycklar finns
const requiredKeys = ['openapi', 'info', 'paths'];
const missingKeys = requiredKeys.filter(key => !(key in parsed));
if (missingKeys.length > 0) {
throw new RapLPBaseApiError(
"Missing required top-level keys",
`Missing required top-level keys: ${missingKeys.join(', ')}`,
ERROR_TYPE.BAD_REQUEST);
}
} catch (error) {
// Handle YAML parsing error
if (error instanceof yaml.YAMLException) {
throw new RapLPBaseApiError(
"Could not validate Yaml",
`YAML Syntax Error: ${error.message}`,
ERROR_TYPE.BAD_REQUEST);
} else if (error instanceof RapLPBaseApiError) {
throw error
} else {
throw new RapLPBaseApiError(
"Failed to validate yaml",
`Could not vaildate yaml: ${error}`,
ERROR_TYPE.INTERNAL_SERVER_ERROR
)
}
}
return true;
}
export function decodeBase64String(base64YamlFile: string) {
// Import the necessary Node.js module (Buffer is built-in)
const atob = (b64String: string): string => Buffer.from(b64String, 'base64').toString('utf-8');
// Decode the base64 string
const decodedYaml = atob(base64YamlFile);
return decodedYaml;
}
export async function processApiSpec(enabledRulesAndCategorys: { rules: Record<string, any>; instanceCategoryMap: Map<string, any>; }, apiSpecDocument: Document<unknown, Parsers.YamlParserResult<unknown>>) {
const customSpectral = new RapLPCustomSpectral();
customSpectral.setCategorys(enabledRulesAndCategorys.instanceCategoryMap);
customSpectral.setRuleset(enabledRulesAndCategorys.rules);
return await customSpectral.run(apiSpecDocument);
}
/**
* https://oida.dev/typescript-hasownproperty/
* @param obj Object to check
* @param prop Property to check for
* @returns Boolean
*/
export function hasOwnProperty<X extends {}, Y extends PropertyKey>
(obj: X, prop: Y): obj is X & Record<Y, unknown> {
return obj.hasOwnProperty(prop)
}