-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathswagger-parser.ts
39 lines (35 loc) · 1.33 KB
/
swagger-parser.ts
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
/* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. */
import { PathLike, readFileSync } from 'fs';
import path from 'path';
import { SwaggerMetadata, SwaggerPath } from './swagger-types';
export function readSwaggerFile(swaggerPath: PathLike): SwaggerMetadata {
const swaggerFile = readFileSync(path.resolve(swaggerPath.toString()), {
encoding: 'utf-8'
});
return parseSwaggerFile(swaggerFile);
}
function parseSwaggerFile(swaggerFile: string): SwaggerMetadata {
const swaggerMetaData = JSON.parse(swaggerFile);
// Get definitions from schema in case there are no definitions present, this is typically the case for openapi files (version >= 3.0.0)
swaggerMetaData.definitions =
swaggerMetaData.definitions || swaggerMetaData?.components?.schemas;
return swaggerMetaData;
}
export function swaggerDefinitionForFunctionImport(
originalName: string,
httpMethod: string,
swaggerMetadata: SwaggerMetadata | undefined
): SwaggerPath | undefined {
if (swaggerMetadata) {
const paths = swaggerMetadata.paths;
const entryPath = Object.keys(paths).find(p => p === `/${originalName}`);
if (entryPath) {
const key = Object.keys(paths[entryPath]).find(
k => k.toLowerCase() === httpMethod.toLowerCase()
);
if (key) {
return paths[entryPath][key];
}
}
}
}