forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operation.js
380 lines (323 loc) · 13.5 KB
/
operation.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
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
#!/usr/bin/env node
import { get, flatten, isPlainObject } from 'lodash-es'
import { sentenceCase } from 'change-case'
import GitHubSlugger from 'github-slugger'
import httpStatusCodes from 'http-status-code'
import renderContent from '../../../lib/render-content/index.js'
import createCodeSamples from './create-code-samples.js'
import Ajv from 'ajv'
import operationSchema from './operation-schema.js'
const slugger = new GitHubSlugger()
// titles that can't be derived by sentence-casing the ID
const categoryTitles = { scim: 'SCIM' }
export default class Operation {
constructor(verb, requestPath, props, serverUrl) {
const defaultProps = {
parameters: [],
'x-codeSamples': [],
responses: {},
}
Object.assign(this, { verb, requestPath, serverUrl }, defaultProps, props)
slugger.reset()
this.slug = slugger.slug(this.summary)
// Add category
// workaround for misnamed `code-scanning.` category bug
// https://github.com/github/rest-api-description/issues/38
this['x-github'].category = this['x-github'].category.replace('.', '')
this.category = this['x-github'].category
this.categoryLabel = categoryTitles[this.category] || sentenceCase(this.category)
// Add subcategory
if (this['x-github'].subcategory) {
this.subcategory = this['x-github'].subcategory
this.subcategoryLabel = sentenceCase(this.subcategory)
}
// Add content type. We only display one example and default
// to the first example defined.
const contentTypes = Object.keys(get(this, 'requestBody.content', []))
this.contentType = contentTypes[0]
return this
}
get schema() {
return operationSchema
}
async process() {
this['x-codeSamples'] = createCodeSamples(this)
await Promise.all([
this.renderDescription(),
this.renderCodeSamples(),
this.renderResponses(),
this.renderParameterDescriptions(),
this.renderBodyParameterDescriptions(),
this.renderPreviewNotes(),
this.renderNotes(),
])
const ajv = new Ajv()
const valid = ajv.validate(this.schema, this)
if (!valid) {
console.error(JSON.stringify(ajv.errors, null, 2))
throw new Error('Invalid operation found')
}
}
async renderDescription() {
this.descriptionHTML = await renderContent(this.description)
return this
}
async renderCodeSamples() {
return Promise.all(
this['x-codeSamples'].map(async (sample) => {
const markdown = createCodeBlock(sample.source, sample.lang.toLowerCase())
sample.html = await renderContent(markdown)
return sample
})
)
}
async renderResponses() {
// clone and delete this.responses so we can turn it into a clean array of objects
const rawResponses = JSON.parse(JSON.stringify(this.responses))
delete this.responses
this.responses = await Promise.all(
Object.keys(rawResponses).map(async (responseCode) => {
const rawResponse = rawResponses[responseCode]
const httpStatusCode = responseCode
const httpStatusMessage = httpStatusCodes.getMessage(Number(responseCode))
const responseDescription = rawResponse.description
const cleanResponses = []
/* Responses can have zero, one, or multiple examples. The `examples`
* property often only contains one example object. Both the `example`
* and `examples` properties can be used in the OpenAPI but `example`
* doesn't work with `$ref`.
* This works:
* schema:
* '$ref': '../../components/schemas/foo.yaml'
* example:
* id: 10
* description: This is a summary
* foo: bar
*
* This doesn't
* schema:
* '$ref': '../../components/schemas/foo.yaml'
* example:
* '$ref': '../../components/examples/bar.yaml'
*/
const examplesProperty = get(rawResponse, 'content.application/json.examples')
const exampleProperty = get(rawResponse, 'content.application/json.example')
// Return early if the response doesn't have an example payload
if (!exampleProperty && !examplesProperty) {
return [
{
httpStatusCode,
httpStatusMessage,
description: responseDescription,
},
]
}
// Use the same format for `example` as `examples` property so that all
// examples can be handled the same way.
const normalizedExampleProperty = {
default: {
value: exampleProperty,
},
}
const rawExamples = examplesProperty || normalizedExampleProperty
const rawExampleKeys = Object.keys(rawExamples)
for (const exampleKey of rawExampleKeys) {
const exampleValue = rawExamples[exampleKey].value
const exampleSummary = rawExamples[exampleKey].summary
const cleanResponse = {
httpStatusCode,
httpStatusMessage,
}
// If there is only one example, use the response description
// property. For cases with more than one example, some don't have
// summary properties with a description, so we can sentence case
// the property name as a fallback
cleanResponse.description =
rawExampleKeys.length === 1
? exampleSummary || responseDescription
: exampleSummary || sentenceCase(exampleKey)
const payloadMarkdown = createCodeBlock(exampleValue, 'json')
cleanResponse.payload = await renderContent(payloadMarkdown)
cleanResponses.push(cleanResponse)
}
return cleanResponses
})
)
// flatten child arrays
this.responses = flatten(this.responses)
}
async renderParameterDescriptions() {
return Promise.all(
this.parameters.map(async (param) => {
param.descriptionHTML = await renderContent(param.description)
return param
})
)
}
async renderBodyParameterDescriptions() {
let bodyParamsObject = get(
this,
`requestBody.content.${this.contentType}.schema.properties`,
{}
)
let requiredParams = get(this, `requestBody.content.${this.contentType}.schema.required`, [])
const oneOfObject = get(this, `requestBody.content.${this.contentType}.schema.oneOf`, undefined)
// oneOf is an array of input parameter options, so we need to either
// use the first option or munge the options together.
if (oneOfObject) {
const firstOneOfObject = oneOfObject[0]
const allOneOfAreObjects =
oneOfObject.filter((elem) => elem.type === 'object').length === oneOfObject.length
// TODO: Remove this check
// This operation shouldn't have a oneOf in this case, it needs to be
// removed from the schema in the github/github repo.
if (this.operationId === 'checks/create') {
delete bodyParamsObject.oneOf
} else if (allOneOfAreObjects) {
// When all of the oneOf objects have the `type: object` we
// need to display all of the parameters.
// This merges all of the properties and required values into the
// first requestBody object.
for (let i = 1; i < oneOfObject.length; i++) {
Object.assign(firstOneOfObject.properties, oneOfObject[i].properties)
requiredParams = firstOneOfObject.required.concat(oneOfObject[i].required)
}
bodyParamsObject = firstOneOfObject.properties
} else if (oneOfObject) {
// When a oneOf exists but the `type` differs, the case has historically
// been that the alternate option is an array, where the first option
// is the array as a property of the object. We need to ensure that the
// first option listed is the most comprehensive and preferred option.
bodyParamsObject = firstOneOfObject.properties
requiredParams = firstOneOfObject.required
}
}
this.bodyParameters = await getBodyParams(bodyParamsObject, requiredParams)
}
async renderPreviewNotes() {
const previews = get(this, 'x-github.previews', []).filter((preview) => preview.note)
return Promise.all(
previews.map(async (preview) => {
const note = preview.note
// remove extra leading and trailing newlines
.replace(/```\n\n\n/gm, '```\n')
.replace(/```\n\n/gm, '```\n')
.replace(/\n\n\n```/gm, '\n```')
.replace(/\n\n```/gm, '\n```')
// convert single-backtick code snippets to fully fenced triple-backtick blocks
// example: This is the description.\n\n`application/vnd.github.machine-man-preview+json`
.replace(/\n`application/, '\n```\napplication')
.replace(/json`$/, 'json\n```')
preview.html = await renderContent(note)
})
)
}
// add additional notes to this array whenever we want
async renderNotes() {
this.notes = []
return Promise.all(this.notes.map(async (note) => renderContent(note)))
}
}
// need to use this function recursively to get child and grandchild params
async function getBodyParams(paramsObject, requiredParams) {
if (!isPlainObject(paramsObject)) return []
return Promise.all(
Object.keys(paramsObject).map(async (paramKey) => {
const param = paramsObject[paramKey]
param.name = paramKey
param.in = 'body'
param.rawType = param.type
param.rawDescription = param.description
// Stores the types listed under the `Type` column in the `Parameters`
// table in the REST API docs. When the parameter contains oneOf
// there are multiple acceptable parameters that we should list.
const paramArray = []
const oneOfArray = param.oneOf
const isOneOfObjectOrArray = oneOfArray
? oneOfArray.filter((elem) => elem.type !== 'object' || elem.type !== 'array')
: false
// When oneOf has the type array or object, the type is defined
// in a child object
if (oneOfArray && isOneOfObjectOrArray.length > 0) {
// Store the defined types
paramArray.push(oneOfArray.filter((elem) => elem.type).map((elem) => elem.type))
// If an object doesn't have a description, it is invalid
const oneOfArrayWithDescription = oneOfArray.filter((elem) => elem.description)
// Use the parent description when set, otherwise enumerate each
// description in the `Description` column of the `Parameters` table.
if (!param.description && oneOfArrayWithDescription.length > 1) {
param.description = oneOfArray
.filter((elem) => elem.description)
.map((elem) => `**Type ${elem.type}** - ${elem.description}`)
.join('\n\n')
} else if (!param.description && oneOfArrayWithDescription.length === 1) {
// When there is only on valid description, use that one.
param.description = oneOfArrayWithDescription[0].description
}
}
// Arrays require modifying the displayed type (e.g., array of strings)
if (param.type === 'array') {
if (param.items.type) paramArray.push(`array of ${param.items.type}s`)
if (param.items.oneOf) {
paramArray.push(param.items.oneOf.map((elem) => `array of ${elem.type}s`))
}
} else if (param.type) {
paramArray.push(param.type)
}
if (param.nullable) paramArray.push('nullable')
param.type = paramArray.flat().join(' or ')
param.description = param.description || ''
const isRequired = requiredParams && requiredParams.includes(param.name)
const requiredString = isRequired ? '**Required**. ' : ''
param.description = await renderContent(requiredString + param.description)
// there may be zero, one, or multiple object parameters that have children parameters
param.childParamsGroups = []
const childParamsGroup = await getChildParamsGroup(param)
if (childParamsGroup && childParamsGroup.params.length) {
param.childParamsGroups.push(childParamsGroup)
}
// if the param is an object, it may have child object params that have child params :/
if (param.rawType === 'object') {
param.childParamsGroups.push(
...flatten(
childParamsGroup.params
.filter((param) => param.childParamsGroups.length)
.map((param) => param.childParamsGroups)
)
)
}
return param
})
)
}
async function getChildParamsGroup(param) {
// only objects, arrays of objects, anyOf, allOf, and oneOf have child params
if (!(param.rawType === 'array' || param.rawType === 'object' || param.oneOf)) return
if (
param.oneOf &&
!param.oneOf.filter((param) => param.type === 'object' || param.type === 'array')
)
return
if (param.items && param.items.type !== 'object') return
const childParamsObject = param.rawType === 'array' ? param.items.properties : param.properties
const requiredParams = param.rawType === 'array' ? param.items.required : param.required
const childParams = await getBodyParams(childParamsObject, requiredParams)
// adjust the type for easier readability in the child table
const parentType = param.rawType === 'array' ? 'items' : param.rawType
// add an ID to the child table so they can be linked to
slugger.reset()
const id = slugger.slug(`${param.name}-${parentType}`)
return {
parentName: param.name,
parentType,
id,
params: childParams,
}
}
function createCodeBlock(input, language) {
// stringify JSON if needed
if (language === 'json' && typeof input !== 'string') {
input = JSON.stringify(input, null, 2)
}
return ['```' + language, input, '```'].join('\n')
}