forked from Avalara/swagger-ts-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
238 lines (211 loc) · 7.88 KB
/
main.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import _ = require('lodash')
import formatter = require('typescript-formatter')
const wordwrap = require('word-wrap')
type SwaggerDoc = {
swagger: string //version
info : any
host : string
'x-swagger-namespace' : string
schemes: string[]
produces: string
basepath?: string
paths : { [path:string] : any }
parameters : any
responses: any
//definitions: { [name:string] : SwaggerType }
}
type SwaggerType = {
type : string
description? : string
maxLength?: number
$ref?: string
format?: string
enum?: (string|number)[]
properties?: { [name:string] : SwaggerType }
items?: any
allOf? : SwaggerType[]
anyOf? : SwaggerType[]
required? : string[]
}
var __mainDoc : SwaggerDoc
var __definitionRoot : string
interface mergeOpts {
external?: any
filename?: string
hideComments?: boolean
//search for type definitions in the following path (currently only 1 item)
searchWithin?: string
}
export async function merge(swaggerDoc, opts : mergeOpts = {}) {
opts.filename = opts.filename || 'typing_' + Math.ceil(Math.random()*10000) + '.d.ts'
__definitionRoot = opts.searchWithin || 'definitions'
__mainDoc = swaggerDoc
var out = '';
let external = opts.external ? 'export ' : ''
if (!Object.keys(swaggerDoc[__definitionRoot]||{}).length) {
throw Error('No definition found in ' + __definitionRoot)
}
for ( let name in swaggerDoc[__definitionRoot] ) {
//if (name !== 'PurchaseHeaderIn') continue
let def : SwaggerType = swaggerDoc[__definitionRoot][name]
let templ = typeTemplate(def,4, true)
let isInterface = ['object','allOf', 'anyOf'].indexOf(templ.type) !== -1
let keyword = isInterface ? 'interface' : 'type'
let equals = isInterface ? '' : ' = '
let extend = ''
if (isInterface && (templ.extends||[]).length) {
extend = 'extends' + ' ' + templ.extends.join(',')
}
out += `
${external}${keyword} ${name} ${extend} ${equals}
${templ.data.join('\n')}
`
}
console.log('dest', opts.filename)
let result = await formatter.processString(opts.filename, out, {
editorconfig: false,
replace: true,
tsconfig: false,
tsfmt: false,
tslint: false,
verify: false
})
return result.dest
function typeTemplate(swaggerType:SwaggerType, indent = 0, embraceObjects = false) {
function wrap() : { data : string[], type : string, extends?: string[] } {
if (swaggerType.$ref) {
let split = swaggerType.$ref.split('/')
return {
data : [split[split.length-1]],
type: 'ref'
}
}
if (swaggerType.enum) {
let typestr = swaggerType.enum.reduce((bef,curr) => {
if (typeof curr === 'string') curr = `'${String(curr).replace(/'/g,"\\'")}'`
if (bef) bef += '|'
bef += String(curr)
return bef
},'')
let wrapped = wrapLiteral(typestr)
return { data: wrapped, type: 'enum' }
}
if (~['integer', 'double', 'number'].indexOf(swaggerType.type)) {
return { data : ['number'], type: 'primitive' }
}
if (~['string','boolean'].indexOf(swaggerType.type)) {
return { data : [swaggerType.type], type: 'primitive' }
}
if (swaggerType.type === 'object' || swaggerType.properties) {
let aux = _.toPairs(swaggerType.properties).map( pair => {
var [key, prop] = pair as [string,SwaggerType]
let current = typeTemplate(prop, indent, true).data
let required = (swaggerType.required && swaggerType.required.indexOf(key) != -1) ?
'' : '?'
current[0] = `${key}${required} : ${current[0].trim()}`
if (prop.description && !opts.hideComments) {
var doc = [
'/**',
...wordwrap(prop.description, {width: 60})
.split('\n').map(s => ` * ${s.trim()}`),
' */'
]
current = [...doc, ...current]
}
return current
})
let joined = aux.reduce((bef,curr)=>[...bef, ...curr],[])
if (embraceObjects) {
//one-liner
if (joined.length === 1) {
joined[0] = `{ ${aux[0]} }`
} else {
joined.unshift('{')
joined.push('}')
}
}
return { data : joined, type: 'object' }
}
if (swaggerType.type === 'array') {
let inner = typeTemplate(swaggerType.items, 0, true).data
inner[inner.length-1] += '[]'
return { data : inner, type: 'array' }
}
if (swaggerType.allOf) {
let merged = mergeAllof(swaggerType)
return {
data : [ '{' , ...typeTemplate(merged.swaggerDoc).data , '}' ],
type: 'allOf' ,
extends : merged.extends
}
}
if (swaggerType.anyOf) {
let merged = mergeAllof(swaggerType, 'anyOf')
return {
data : [ '{' , ...typeTemplate(merged.swaggerDoc).data , '}' ],
type: 'anyOf',
extends : merged.extends
}
}
throw swaggerType.type
}
let out = wrap()
return {
data : out.data.map( ln => _.repeat(' ',indent) + ln),
type : out.type,
extends: out.extends
}
}
}
function mergeAllof( swaggerType:SwaggerType, key : 'allOf'|'anyOf' = 'allOf' ) {
let item = swaggerType[key]
if (!item) throw Error('wrong mergeAllOf call.')
var extend = [];
let merged = item.reduce( (prev, toMerge) => {
let refd : SwaggerType
if (toMerge.$ref) {
let split = toMerge.$ref.split('/')
if (split[0] === '#' && split[1] === __definitionRoot && split.length === 3) {
extend.push(split[2])
return prev
}
refd = findDef(__mainDoc, split)
}
else {
refd = toMerge
}
if (refd.allOf) refd = mergeAllof(refd, 'allOf').swaggerDoc
else if (refd.anyOf) refd = mergeAllof(refd, 'anyOf').swaggerDoc
if (!refd.properties) {
console.error('allOf merge: unsupported object type at ' + JSON.stringify(toMerge))
}
for ( var it in <any>refd.properties ) {
//if ((<any>prev).properties[it]) console.error('property', it, 'overwritten in ', JSON.stringify(toMerge).substr(0,80));
;(<any>prev).properties[it] = (<any>refd).properties[it]
}
return prev
},{ type : 'object', properties : {}})
return { swaggerDoc : merged, extends: extend }
}
function findDef(src, path:string[]) {
if(path[0] == '#') path = path.slice(1)
if (!path.length) return src
return findDef(src[path[0]], path.slice(1))
}
function wrapLiteral(inp) {
let items = inp.split('|')
let allLines : string[] = []
let currentLine = ''
items.forEach( i => {
currentLine += i + '|'
if (currentLine.length > 40) {
allLines.push(currentLine)
currentLine = ''
}
})
if(currentLine) {allLines.push(currentLine)}
let last = allLines[allLines.length-1]
last = last.substr(0, last.length-1)
allLines[allLines.length-1] = last
return allLines
}