-
Notifications
You must be signed in to change notification settings - Fork 11
/
generateOptionsFromSpec.ts
68 lines (65 loc) · 2.2 KB
/
generateOptionsFromSpec.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
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
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import SwaggerParser from '@apidevtools/swagger-parser';
import { createWriteStream } from 'node:fs';
import { OpenAPIV3 } from 'openapi-types';
const EXTRACT_PROPERTIES = [
'ProjectCreateRequest',
'ProjectUpdateRequest',
'BranchCreateRequest',
'BranchCreateRequestEndpointOptions',
'BranchUpdateRequest',
'EndpointCreateRequest',
'EndpointUpdateRequest',
'DatabaseCreateRequest',
'RoleCreateRequest',
];
const typesMapping = {
array: 'array',
integer: 'number',
string: 'string',
boolean: 'boolean',
} as const;
(async () => {
const spec: OpenAPIV3.Document = (await SwaggerParser.dereference(
'./node_modules/@neondatabase/api-client/public-v2.yaml',
)) as any;
const outFile = createWriteStream('./src/parameters.gen.ts', 'utf8');
outFile.write('// FILE IS GENERATED, DO NOT EDIT\n\n');
EXTRACT_PROPERTIES.forEach((name) => {
const schema = spec.components?.schemas?.[name] as OpenAPIV3.SchemaObject;
const parseProperties = (
schema: OpenAPIV3.SchemaObject,
context: string[] = [],
) => {
Object.entries(
schema.properties as Record<string, OpenAPIV3.SchemaObject>,
).forEach(([key, value]) => {
if (value.type === 'object' && value.properties) {
parseProperties(value, [...context, key]);
} else if (value.type! in typesMapping) {
outFile.write(
` '${[...context, key].join('.')}': {
type: ${JSON.stringify(
typesMapping[value.type as keyof typeof typesMapping],
)},
description: ${JSON.stringify(value.description)},
demandOption: ${
schema.required?.includes(key) ? 'true' : 'false'
},\n`,
);
if (value.enum) {
outFile.write(` choices: ${JSON.stringify(value.enum)},\n`);
}
outFile.write(' },\n');
}
});
};
outFile.write(
`export const ${name[0].toLowerCase()}${name.slice(1)} = {\n`,
);
parseProperties(schema);
outFile.write(`} as const;\n\n`);
});
outFile.end();
})();