forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-code-samples.js
163 lines (140 loc) · 4.92 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
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: 'octocat@github.com',
emails: ['octocat@github.com']
}
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'
const args = [
method !== 'GET' && `-X ${method}`,
defaultAcceptHeader ? `-H "Accept: ${defaultAcceptHeader}"` : '',
`${serverUrl}${path}`,
Object.keys(params).length && `-d '${JSON.stringify(params)}'`
].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 }) {
let schema
try {
schema = operation.requestBody.content['application/json'].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)}`)
}