/
base.path.ts
35 lines (31 loc) 路 1.13 KB
/
base.path.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
import { OpenAPIV3 } from 'openapi-types';
import { URL } from 'url';
export default class BasePath {
public readonly variables: { [key: string]: { enum: string[] } } = {};
public readonly path: string = '';
constructor(server: OpenAPIV3.ServerObject) {
// break the url into parts
// baseUrl param added to make the parsing of relative paths go well
const serverUrl = new URL(server.url, 'http://localhost');
let urlPath = decodeURI(serverUrl.pathname).replace(/\/$/, '');
if (/{\w+}/.test(urlPath)) {
// has variable that we need to check out
urlPath = urlPath.replace(/{(\w+)}/g, (substring, p1) => `:${p1}`);
}
this.path = urlPath;
for (const variable in server.variables) {
if (server.variables.hasOwnProperty(variable)) {
this.variables[variable] = { enum: server.variables[variable].enum };
}
}
}
public hasVariables() {
return Object.keys(this.variables).length > 0;
}
public static fromServers(servers: OpenAPIV3.ServerObject[]) {
if (!servers) {
return [new BasePath({ url: '' })];
}
return servers.map(server => new BasePath(server));
}
}