/
index.ts
381 lines (373 loc) · 12.5 KB
/
index.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import marked from 'marked'
import yaml from 'js-yaml'
import pluralize from 'pluralize'
import swagger from 'swagger-parser'
import { OpenAPIV2 } from 'openapi-types'
import { cloneDeep } from 'lodash'
import camelCase from 'camelcase'
import jsf from 'json-schema-faker'
import AWS from 'aws-sdk'
/**
* Uses the marked lexer to extract tokens from the Markdown document
* @param document the Markdown document, as a string
*/
export const tokens = async (document: string): Promise<marked.TokensList> => {
try {
return marked.lexer(document)
} catch (error) {
throw new Error(`Error while parsing the Markdown document: ${error.message}`)
}
}
/**
* Finds Markdown code blocks in the token list, and combines them into a YAML string containing schemas
* @param tokens the Markdown tokens
*/
export const schemas = async (tokens: marked.TokensList): Promise<string> => {
try {
return tokens.reduce((combined, token) => {
if (token.type === 'code' && token.text.length > 0) {
if (token.lang === 'json') {
return combined += `${yaml.safeDump(JSON.parse(token.text), { noRefs: true })}\n`
}
if (token.lang === 'yaml') {
return combined += `${token.text}\n`
}
}
return combined
}, '')
} catch (error) {
throw new Error(`Error while extracting schemas from the Markdown document: ${error.message}`)
}
}
/**
* Finds the first top-level (h1) Markdown heading in the token list, and normalizes it.
* Normalization turns the title into all lowercase with dashes instead of spaces.
* @param tokens the Markdown tokens
*/
export const title = async (tokens: marked.TokensList): Promise<string> => {
try {
let heading = tokens.find(token => token.type === 'heading' && token.depth == 1) as marked.Tokens.Heading
if (!heading || !heading.text || heading.text.length == 0)
throw new Error('No heading found in the document. Specify a heading like "# Some heading"')
return heading.text.toLowerCase().split(' ').join('-')
} catch (error) {
throw new Error(`Error while getting title from the Markdown document: ${error.message}`)
}
}
/**
* Creates a Swagger API specification with CRUD operations for each schema
* @param schemas the combined schemas string
*/
export const specification = async (schemas: string, title: string): Promise<OpenAPIV2.Document> => {
try {
// build a swagger definition from schemas
let specification: OpenAPIV2.Document = {
swagger: '2.0',
info: {
title,
version: '1.0.0'
},
consumes: [ 'application/json' ],
produces: [ 'application/json' ],
tags: [],
paths: {},
definitions: yaml.safeLoad(schemas)
}
// validate schemas
await swagger.validate(cloneDeep(specification))
// build all default routes for all resources
for (let key of Object.keys(specification.definitions)) {
let collection = pluralize(key)
specification.tags.push({ name: collection })
specification.paths[`/${collection}`] = {
get: {
operationId: camelCase([ 'get', collection ]),
tags: [ collection ],
responses: {
'200': {
description: '200 OK',
schema: {
type: 'array',
items: {
$ref: `#/definitions/${key}`
}
}
}
}
},
post: {
operationId: camelCase([ 'post', collection ]),
tags: [ collection ],
parameters: [
{
name: key,
in: 'body',
required: true,
schema: {
$ref: `#/definitions/${key}`
}
}
],
responses: {
'201': {
description: '201 Created',
schema: {
$ref: `#/definitions/${key}`
}
}
}
},
options: {
operationId: camelCase([ 'options', collection ]),
tags: [ 'cors' ],
responses: {
'200': {
description: '200 OK',
headers: {
'Access-Control-Allow-Headers': {
type: 'string'
},
'Access-Control-Allow-Methods': {
type: 'string'
},
'Access-Control-Allow-Origin': {
type: 'string'
}
}
}
}
}
}
specification.paths[`/${collection}/{${key}Id}`] = {
get: {
operationId: camelCase([ 'get', key ]),
tags: [ collection ],
parameters: [
{
name: `${key}Id`,
in: 'path',
required: true,
type: 'integer',
format: 'int64'
}
],
responses: {
'200': {
description: '200 OK',
schema: {
$ref: `#/definitions/${key}`
}
}
}
},
put: {
operationId: camelCase([ 'put', key ]),
tags: [ collection ],
parameters: [
{
name: `${key}Id`,
in: 'path',
required: true,
type: 'integer',
format: 'int64'
},
{
name: key,
in: 'body',
required: true,
schema: {
$ref: `#/definitions/${key}`
}
}
],
responses: {
'204': {
description: '204 No Content'
}
}
},
delete: {
operationId: camelCase([ 'delete', key ]),
tags: [ collection ],
parameters: [
{
name: `${key}Id`,
in: 'path',
required: true,
type: 'integer',
format: 'int64'
}
],
responses: {
'204': {
description: '204 No Content'
}
}
},
options: {
operationId: camelCase([ 'options', key ]),
tags: [ 'cors' ],
parameters: [
{
name: `${key}Id`,
in: 'path',
required: true,
type: 'integer',
format: 'int64'
}
],
responses: {
'200': {
description: '200 OK',
headers: {
'Access-Control-Allow-Headers': {
type: 'string'
},
'Access-Control-Allow-Methods': {
type: 'string'
},
'Access-Control-Allow-Origin': {
type: 'string'
}
}
}
}
}
}
}
// validate swagger definition against the official swagger schema and spec
await swagger.validate(cloneDeep(specification))
// bundle and use internal $refs
specification = await swagger.bundle(specification) as OpenAPIV2.Document
return specification
} catch (error) {
throw new Error(`Error while generating the swagger specification from the document: ${error.message}`)
}
}
/**
* Adds the AWS API Gateway request validation and mock integrations to the Swagger API specification
* @param specification the Swagger API specification object
*/
export const mocks = async (specification: OpenAPIV2.Document): Promise<OpenAPIV2.Document> => {
try {
// validate and dereference the specification
specification = await swagger.validate(specification) as OpenAPIV2.Document
specification['x-amazon-apigateway-request-validators'] = {
validateBodyAndParameters: {
validateRequestBody: true,
validateRequestParameters: true
}
}
specification['x-amazon-apigateway-request-validator'] = 'validateBodyAndParameters'
for (let pathKey of Object.keys(specification.paths)) {
for (let operationKey of Object.keys(specification.paths[pathKey])) {
let responses = specification.paths[pathKey][operationKey].responses
let status = Object.keys(responses)[0]
let schema = responses[status].schema
let mockData: any
if (schema) mockData = await jsf.resolve(schema)
specification.paths[pathKey][operationKey]['x-amazon-apigateway-integration'] = {
type: 'mock',
requestTemplates: {
'application/json': '{\"statusCode\": 200}'
},
responses: {
default: (operationKey === 'options') ? {
statusCode: '200',
responseParameters: {
'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'",
'method.response.header.Access-Control-Allow-Methods': "'*'",
'method.response.header.Access-Control-Allow-Origin': "'*'"
},
responseTemplates: {
'application/json': '{}'
}
} : (mockData) ? {
statusCode: `${status}`,
responseTemplates: {
'application/json': JSON.stringify(mockData, null, 2)
}
} : {
statusCode: `${status}`
}
},
passthroughBehavior: 'when_no_match'
}
}
}
specification = await swagger.validate(specification) as OpenAPIV2.Document
return specification
} catch (error) {
throw new Error(`Error while generating the mock integrations for the swagger specification: ${error.message}`)
}
}
export interface Deploy {
id: string
url: string
}
/**
* Deploys the Swagger API specification to AWS API Gateway
* @param specification the Swagger API specification object
* @param id the id of the existing API to update instead of deploying new
*/
export const deploy = async (specification: OpenAPIV2.Document, id?: string): Promise<Deploy> => {
try {
let gateway = new AWS.APIGateway({
apiVersion: '2015-07-09',
credentialProvider: new AWS.CredentialProviderChain([
() => new AWS.EnvironmentCredentials('AWS'),
() => new AWS.SharedIniFileCredentials()
])
})
let errorMessage = ''
if (!gateway.config.region) errorMessage += 'Please specify an AWS_REGION as an environment variable or in the AWS config file.\n'
if (!gateway.config.credentials) errorMessage += 'Please specify an AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or AWS_PROFILE) as environment variables.\n'
if (!gateway.config.region || !gateway.config.credentials) throw new Error(`Missing AWS configuration.\n${errorMessage}`)
if (id && id.length > 0) {
await gateway.putRestApi({
restApiId: id,
failOnWarnings: true,
mode: 'overwrite',
body: JSON.stringify(specification, null, 2)
}).promise()
} else {
let importResponse = await gateway.importRestApi({
body: JSON.stringify(specification, null, 2),
failOnWarnings: true
}).promise()
id = importResponse.id
}
let deploymentResponse = await gateway.createDeployment({
restApiId: id,
stageName: 'dev'
}).promise()
return {
id,
url: `https://${id}.execute-api.${gateway.config.region}.amazonaws.com/dev`
}
} catch (error) {
throw new Error(`Error while deploying the swagger specification to the AWS API Gateway: ${error.message}`)
}
}
/**
* Undeploys the API from the AWS API Gateway
* @param id the id of the existing API to remove
*/
export const undeploy = async (id: string): Promise<void> => {
try {
let gateway = new AWS.APIGateway({
apiVersion: '2015-07-09',
credentialProvider: new AWS.CredentialProviderChain([
() => new AWS.EnvironmentCredentials('AWS'),
() => new AWS.SharedIniFileCredentials()
])
})
let errorMessage = ''
if (!gateway.config.region) errorMessage += 'Please specify an AWS_REGION as an environment variable or in the AWS config file.\n'
if (!gateway.config.credentials) errorMessage += 'Please specify an AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or AWS_PROFILE) as environment variables.\n'
if (!gateway.config.region || !gateway.config.credentials) throw new Error(`Missing AWS configuration.\n${errorMessage}`)
await gateway.deleteRestApi({ restApiId: id }).promise()
} catch (error) {
throw new Error(`Error while undeploying the API from AWS API Gateway: ${error.message}`)
}
}