This repository has been archived by the owner on Jul 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
generateApi.js
71 lines (65 loc) · 1.87 KB
/
generateApi.js
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
/**
* This script is used to generate the API client for this project from openapi.json.
* Also, we need to add a line of comment to disable errors generated by ts-check.
*/
const { generateApi } = require('swagger-typescript-api')
const path = require('path')
const fs = require('fs')
const { EOL } = require('os')
const envOpts = {
submodule: 'submodule',
localServer: 'localServer',
stagingServer: 'stagingServer'
}
const urlMapping = {
[envOpts.localServer]: 'http://localhost:34765/api/v1/openapi.json',
[envOpts.stagingServer]: 'http://nichujie.xyz/api/v1/openapi.json'
}
const outputPath = path.resolve(process.cwd(), 'src/client')
const env = process.argv[2] ?? envOpts.submodule
if (
env !== envOpts.submodule &&
env !== envOpts.localServer &&
env !== envOpts.stagingServer
) {
console.error(
'ERROR: wrong environment option. Valid options: submodule, localServer, stagingServer'
)
process.exit(-1)
}
let config
if (env === envOpts.submodule) {
config = {
name: 'index.ts',
output: outputPath,
input: path.resolve(process.cwd(), 'openapi/openapi.json'),
templates: path.resolve(process.cwd(), './api-templates'),
httpClientType: 'axios',
moduleNameFirstTag: true
}
} else {
config = {
name: 'index.ts',
output: outputPath,
url: urlMapping[env],
templates: path.resolve(process.cwd(), './api-templates'),
httpClientType: 'axios',
moduleNameFirstTag: true
}
}
console.log('Start to generate API client for ' + env)
generateApi(config)
.then(({ files }) => {
files.forEach(({ name }) => {
const generatedFilePath = path.resolve(outputPath, name)
const data = fs.readFileSync(generatedFilePath)
fs.writeFile(
generatedFilePath,
'// @ts-nocheck generated file' + EOL + data,
err => {
if (err) throw err
}
)
})
})
.catch(e => console.error(e))