forked from Tinkoff/swagger-types-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.ts
146 lines (121 loc) · 4.97 KB
/
generator.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import { join } from 'path';
import { readFileSync, writeFileSync } from 'fs';
import mergeDeep from '@tinkoff/utils/object/mergeDeep';
import objectPath from '@tinkoff/utils/object/path';
import YAML from 'yamljs';
import superAgent from 'superagent';
import debug from 'debug';
import { Config } from './types';
import { processingProperties, processingAllOf } from './utils/parse';
import { generateTypes, generatingActionsTypes } from './utils/generate';
import map from './utils/map';
import getTypeAlias from './utils/getTypeAlias';
const log = debug('swagger_types_generator:generator:info');
export default function generator() {
const [, , pathToConfig] = process.argv;
if (!pathToConfig) {
// tslint:disable-next-line:no-console
console.log('Path to config required!');
return;
}
const sourceConfig = require(join(process.cwd(), pathToConfig));
const config: Config = sourceConfig.default || sourceConfig;
const { isActionsEnable } = config;
getSchemas(config)
.then(parseSchemas)
.then(({ types, methods }) => {
log('Generating types…');
generateTypes({ types, config });
if (isActionsEnable) {
log('Generating actions types…');
generatingActionsTypes({ types, methods, config });
}
log('Done!');
});
}
function getSchemas(config: Config) {
const { schemas, projectDir, isCachingEnable } = config;
log(`Get schemas, total ${schemas.length}, caching: ${isCachingEnable}`);
return Promise.all(
schemas.map(({ url, namespace, fileName, format }) => {
const cacheFilePath = join(projectDir, fileName);
return (isCachingEnable
? getCachedSchema(cacheFilePath).then((schema) => ({ namespace, schema }))
: Promise.reject()
).catch(() => {
log(`Request schema, url: ${url}`);
return superAgent
.get(url)
.then((response) => (format === 'yaml' ? YAML.parse(response.text) : response.body))
.then((schema) => {
if (isCachingEnable) {
writeFileSync(cacheFilePath, JSON.stringify(schema));
}
return { schema, namespace };
});
});
})
);
}
function getCachedSchema(path) {
log(`Read cached schema, path: ${path}`);
try {
return Promise.resolve(JSON.parse(readFileSync(path, 'utf-8')));
} catch {
return Promise.reject();
}
}
function parseSchemas(schemas: { schema: any; namespace?: string }[]) {
const syntheticTypes = {};
const types = {};
let methods = {};
log('Parse schemas…');
schemas.forEach(({ schema, namespace = 'default' }) => {
syntheticTypes[namespace] = syntheticTypes[namespace] || {};
types[namespace] = {
...types[namespace],
...map((sourceName, { properties: sourceProperties, required, allOf }: any) => {
if (allOf) {
return processingAllOf({
allOf,
});
}
return processingProperties({
sourceName,
sourceProperties,
required,
isCamelCase: Boolean(schema.definitions),
registerSyntheticType: (type) => {
syntheticTypes[namespace] = {
...syntheticTypes[namespace],
...type,
};
},
});
}, schema.definitions || schema.components.schemas),
};
methods = {
...methods,
...map((methodName, { post, get, put, delete: deleteMethod }: any) => {
const responseDescription = post || get || put || deleteMethod;
if (!responseDescription) {
return;
}
const { parameters: sourceParameters = [], responses: sourceResponses } = responseDescription;
const result = {} as any;
const parameters = objectPath(['schema'], sourceParameters.find(({ name }) => name === 'payload'));
if (parameters) {
const type = parameters.type || (parameters.$ref && parameters.$ref.split('/').pop());
result.parameters = { type: getTypeAlias(type) };
}
const responses = objectPath(['schema'], sourceResponses[200]);
if (responses) {
const type = responses.type || (responses.$ref && responses.$ref.split('/').pop());
result.responses = { type: getTypeAlias(type) };
}
return result;
}, schema.paths),
};
});
return { methods, types: mergeDeep(types, syntheticTypes) };
}