forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-code-samples.js
176 lines (152 loc) · 5.52 KB
/
create-code-samples.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
module.exports = createCodeSamples
const urlTemplate = require('url-template')
const { stringify } = require('javascript-stringify')
const { get, mapValues, snakeCase } = require('lodash')
const PARAMETER_EXAMPLES = {
owner: 'octocat',
repo: 'hello-world',
email: '[email protected]',
emails: ['[email protected]']
}
function createCodeSamples (operation) {
const route = {
method: operation.verb.toUpperCase(),
path: operation.requestPath,
operation
}
const serverUrl = operation.serverUrl
const codeSampleParams = { route, serverUrl }
return [
{ lang: 'Shell', source: toShellExample(codeSampleParams) },
{ lang: 'JavaScript', source: toJsExample(codeSampleParams) }
]
}
function toShellExample ({ route, serverUrl }) {
const pathParams = mapValues(getExamplePathParams(route), (value, paramName) =>
PARAMETER_EXAMPLES[paramName] ? value : snakeCase(value).toUpperCase()
)
const path = urlTemplate.parse(route.path.replace(/:(\w+)/g, '{$1}')).expand(pathParams)
const params = getExampleBodyParams(route)
const { method } = route
const requiredPreview = get(route, 'operation.x-github.previews', [])
.find(preview => preview.required)
const defaultAcceptHeader = requiredPreview
? `application/vnd.github.${requiredPreview.name}-preview+json`
: 'application/vnd.github.v3+json'
let requestBodyParams = `-d '${JSON.stringify(params)}'`
// If the content type is application/x-www-form-urlencoded the format of
// the shell example is --data-urlencode param1=value1 --data-urlencode param2=value2
if (route.operation.contentType === 'application/x-www-form-urlencoded') {
requestBodyParams = ''
const paramNames = Object.keys(params)
paramNames.forEach(elem => {
requestBodyParams = `${requestBodyParams} --data-urlencode ${elem}=${params[elem]}`
})
requestBodyParams = requestBodyParams.trim()
}
const args = [
method !== 'GET' && `-X ${method}`,
defaultAcceptHeader ? `-H "Accept: ${defaultAcceptHeader}"` : '',
`${serverUrl}${path}`,
Object.keys(params).length && requestBodyParams
].filter(Boolean)
return `curl \\\n ${args.join(' \\\n ')}`
}
function toJsExample ({ route }) {
const params = route.operation.parameters
.filter(param => !param.deprecated)
.filter(param => param.in !== 'header')
.filter(param => param.required)
.reduce(
(_params, param) =>
Object.assign(_params, {
[param.name]: getExampleParamValue(param.name, param.schema)
}),
{}
)
Object.assign(params, getExampleBodyParams(route))
// add any required preview headers to the params object
const requiredPreviewNames = get(route.operation, 'x-github.previews', [])
.filter(preview => preview.required)
.map(preview => preview.name)
if (requiredPreviewNames.length) {
Object.assign(params, {
mediaType: { previews: requiredPreviewNames }
})
}
// add required content type header (presently only for `POST /markdown/raw`)
const contentTypeHeader = route.operation.parameters.find(param => {
return param.name.toLowerCase() === 'content-type' && get(param, 'schema.enum')
})
if (contentTypeHeader) {
Object.assign(params, {
headers: { 'content-type': contentTypeHeader.schema.enum[0] }
})
}
const args = Object.keys(params).length ? ', ' + stringify(params, null, 2) : ''
return `await octokit.request('${route.method} ${route.path}'${args})`
}
function getExamplePathParams ({ operation }) {
const pathParams = operation.parameters.filter(param => param.in === 'path')
if (pathParams.length === 0) {
return {}
}
return pathParams.reduce((dict, param) => {
dict[param.name] = getExampleParamValue(param.name, param.schema)
return dict
}, {})
}
function getExampleBodyParams ({ operation }) {
const contentType = Object.keys(get(operation, 'requestBody.content', []))[0]
let schema
try {
schema = operation.requestBody.content[contentType].schema
if (!schema.properties) return {}
} catch (noRequestBody) {
return {}
}
if (operation['x-github'].requestBodyParameterName) {
const paramName = operation['x-github'].requestBodyParameterName
return { [paramName]: getExampleParamValue(paramName, schema) }
}
if (schema.oneOf && schema.oneOf[0].type) {
schema = schema.oneOf[0]
} else if (schema.anyOf && schema.anyOf[0].type) {
schema = schema.anyOf[0]
}
const props =
schema.required && schema.required.length > 0
? schema.required
: Object.keys(schema.properties).slice(0, 1)
return props.reduce((dict, propName) => {
const propSchema = schema.properties[propName]
if (!propSchema.deprecated) {
dict[propName] = getExampleParamValue(propName, propSchema)
}
return dict
}, {})
}
function getExampleParamValue (name, schema) {
const value = PARAMETER_EXAMPLES[name]
if (value) {
return value
}
// TODO: figure out the right behavior here
if (schema.oneOf && schema.oneOf[0].type) return getExampleParamValue(name, schema.oneOf[0])
if (schema.anyOf && schema.anyOf[0].type) return getExampleParamValue(name, schema.anyOf[0])
switch (schema.type) {
case 'string':
return name
case 'boolean':
return true
case 'integer':
return 42
case 'object':
return mapValues(schema.properties, (propSchema, propName) =>
getExampleParamValue(propName, propSchema)
)
case 'array':
return [getExampleParamValue(name, schema.items)]
}
throw new Error(`Unknown data type in schema:, ${JSON.stringify(schema, null, 2)}`)
}