-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate.ts
More file actions
71 lines (60 loc) · 2.16 KB
/
Copy pathgenerate.ts
File metadata and controls
71 lines (60 loc) · 2.16 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
import { spawn } from 'node:child_process'
import { readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import yaml from 'yaml'
export const description = 'Generate OpenAPI types and validate the spec'
export const positional = '<filepath>'
export const run = async (argv: any): Promise<void> => {
console.log('Generating OpenAPI types and validate the spec...')
const yamlFilePath = argv.filepath
const tsFilePath = path.join(
path.dirname(argv.filepath),
`${path.basename(argv.filepath, path.extname(argv.filepath))}.ts`
)
await new Promise((resolve, reject) => {
const process = spawn(
'npx',
['openapi-typescript', yamlFilePath, '--output', tsFilePath],
{ stdio: 'inherit' }
)
process.on('exit', resolve)
process.on('error', reject)
})
console.log('Generating path mappings...')
const types = readFileSync(tsFilePath)
const spec = yaml.parse(readFileSync(yamlFilePath).toString())
const pathsWithOperationIds = Object.keys(spec.paths).reduce((acc, path) => {
const pathSpec = spec.paths[path]
Object.keys(pathSpec).forEach(method => {
if (pathSpec[method]?.operationId) {
const operationResponses = pathSpec[method].responses ?? {}
const responseCodes = Object.keys(operationResponses)
const successStatus = responseCodes.find(s => s.startsWith('2'))
?? responseCodes.find(s => s.startsWith('3'))
?? '200';
acc[pathSpec[method].operationId] = {
method,
path,
successStatus: parseInt(successStatus, 10),
}
}
})
return acc
}, {} as any)
const finalSpec =
`/* eslint-disable sonarjs/no-duplicate-string */\n` +
`/* eslint-disable sonarjs/use-type-alias */\n` +
types.toString('utf8').replaceAll('requestBody?:', 'requestBody:') +
`export const operationPaths = ${JSON.stringify(
pathsWithOperationIds
)} as const\n`
writeFileSync(tsFilePath, finalSpec)
console.log('Done 🎉')
}
export const options = (yargs: any) => {
return yargs.positional('filepath', {
required: true,
type: 'string',
description: 'Input OpenAPI specification file',
})
}