Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

create-code-samples.js 4.9 KB

You have to be logged in to leave a comment. Sign In
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
  1. module.exports = createCodeSamples
  2. const urlTemplate = require('url-template')
  3. const { stringify } = require('javascript-stringify')
  4. const { get, mapValues, snakeCase } = require('lodash')
  5. const PARAMETER_EXAMPLES = {
  6. owner: 'octocat',
  7. repo: 'hello-world',
  8. email: 'octocat@github.com',
  9. emails: ['octocat@github.com']
  10. }
  11. function createCodeSamples (operation) {
  12. const route = {
  13. method: operation.verb.toUpperCase(),
  14. path: operation.requestPath,
  15. operation
  16. }
  17. const serverUrl = operation.serverUrl
  18. const codeSampleParams = { route, serverUrl }
  19. return [
  20. { lang: 'Shell', source: toShellExample(codeSampleParams) },
  21. { lang: 'JavaScript', source: toJsExample(codeSampleParams) }
  22. ]
  23. }
  24. function toShellExample ({ route, serverUrl }) {
  25. const pathParams = mapValues(getExamplePathParams(route), (value, paramName) =>
  26. PARAMETER_EXAMPLES[paramName] ? value : snakeCase(value).toUpperCase()
  27. )
  28. const path = urlTemplate.parse(route.path.replace(/:(\w+)/g, '{$1}')).expand(pathParams)
  29. const params = getExampleBodyParams(route)
  30. const { method } = route
  31. const requiredPreview = get(route, 'operation.x-github.previews', [])
  32. .find(preview => preview.required)
  33. const defaultAcceptHeader = requiredPreview
  34. ? `application/vnd.github.${requiredPreview.name}-preview+json`
  35. : 'application/vnd.github.v3+json'
  36. const args = [
  37. method !== 'GET' && `-X ${method}`,
  38. defaultAcceptHeader ? `-H "Accept: ${defaultAcceptHeader}"` : '',
  39. `${serverUrl}${path}`,
  40. Object.keys(params).length && `-d '${JSON.stringify(params)}'`
  41. ].filter(Boolean)
  42. return `curl \\\n ${args.join(' \\\n ')}`
  43. }
  44. function toJsExample ({ route }) {
  45. const params = route.operation.parameters
  46. .filter(param => !param.deprecated)
  47. .filter(param => param.in !== 'header')
  48. .filter(param => param.required)
  49. .reduce(
  50. (_params, param) =>
  51. Object.assign(_params, {
  52. [param.name]: getExampleParamValue(param.name, param.schema)
  53. }),
  54. {}
  55. )
  56. Object.assign(params, getExampleBodyParams(route))
  57. // add any required preview headers to the params object
  58. const requiredPreviewNames = get(route.operation, 'x-github.previews', [])
  59. .filter(preview => preview.required)
  60. .map(preview => preview.name)
  61. if (requiredPreviewNames.length) {
  62. Object.assign(params, {
  63. mediaType: { previews: requiredPreviewNames }
  64. })
  65. }
  66. // add required content type header (presently only for `POST /markdown/raw`)
  67. const contentTypeHeader = route.operation.parameters.find(param => {
  68. return param.name.toLowerCase() === 'content-type' && get(param, 'schema.enum')
  69. })
  70. if (contentTypeHeader) {
  71. Object.assign(params, {
  72. headers: { 'content-type': contentTypeHeader.schema.enum[0] }
  73. })
  74. }
  75. const args = Object.keys(params).length ? ', ' + stringify(params, null, 2) : ''
  76. return `await octokit.request('${route.method} ${route.path}'${args})`
  77. }
  78. function getExamplePathParams ({ operation }) {
  79. const pathParams = operation.parameters.filter(param => param.in === 'path')
  80. if (pathParams.length === 0) {
  81. return {}
  82. }
  83. return pathParams.reduce((dict, param) => {
  84. dict[param.name] = getExampleParamValue(param.name, param.schema)
  85. return dict
  86. }, {})
  87. }
  88. function getExampleBodyParams ({ operation }) {
  89. let schema
  90. try {
  91. schema = operation.requestBody.content['application/json'].schema
  92. if (!schema.properties) return {}
  93. } catch (noRequestBody) {
  94. return {}
  95. }
  96. if (operation['x-github'].requestBodyParameterName) {
  97. const paramName = operation['x-github'].requestBodyParameterName
  98. return { [paramName]: getExampleParamValue(paramName, schema) }
  99. }
  100. if (schema.oneOf && schema.oneOf[0].type) {
  101. schema = schema.oneOf[0]
  102. } else if (schema.anyOf && schema.anyOf[0].type) {
  103. schema = schema.anyOf[0]
  104. }
  105. const props =
  106. schema.required && schema.required.length > 0
  107. ? schema.required
  108. : Object.keys(schema.properties).slice(0, 1)
  109. return props.reduce((dict, propName) => {
  110. const propSchema = schema.properties[propName]
  111. if (!propSchema.deprecated) {
  112. dict[propName] = getExampleParamValue(propName, propSchema)
  113. }
  114. return dict
  115. }, {})
  116. }
  117. function getExampleParamValue (name, schema) {
  118. const value = PARAMETER_EXAMPLES[name]
  119. if (value) {
  120. return value
  121. }
  122. // TODO: figure out the right behavior here
  123. if (schema.oneOf && schema.oneOf[0].type) return getExampleParamValue(name, schema.oneOf[0])
  124. if (schema.anyOf && schema.anyOf[0].type) return getExampleParamValue(name, schema.anyOf[0])
  125. switch (schema.type) {
  126. case 'string':
  127. return name
  128. case 'boolean':
  129. return true
  130. case 'integer':
  131. return 42
  132. case 'object':
  133. return mapValues(schema.properties, (propSchema, propName) =>
  134. getExampleParamValue(propName, propSchema)
  135. )
  136. case 'array':
  137. return [getExampleParamValue(name, schema.items)]
  138. }
  139. throw new Error(`Unknown data type in schema:, ${JSON.stringify(schema, null, 2)}`)
  140. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...