-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdev-docs-openapi.js
More file actions
329 lines (275 loc) · 9.96 KB
/
dev-docs-openapi.js
File metadata and controls
329 lines (275 loc) · 9.96 KB
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
var Converter = require("openapi-to-postmanv2");
const fs = require("fs");
const importer = require("./extractTwo")
function parseOpenApiInfo(openapiData) {
const operation = openapiData.api;
const headers = {};
const body = {};
const query = {};
// Parse security schemes
if (operation.securitySchemes) {
for (const [schemeName, schemeData] of Object.entries(operation.securitySchemes)) {
switch (schemeData.type) {
case "apiKey":
if (schemeData.in === "header") {
headers[schemeData.name] = "[API Key]"; // Placeholder for actual key
}
break;
case "oauth2":
// Handle OAuth2 details based on flow type
break;
default:
// Handle other security scheme types
break;
}
}
}
// Parse request body schema
if (operation.requestBody) {
const content = operation.requestBody.content["application/json"];
if (content && content.schema) {
const schema = content.schema;
parseSchema(schema, "", body);
}
}
// Parse path parameters (simulated as query for simplicity)
const pathParams = operation.path.match(/\{[^}]+\}/g);
if (pathParams) {
for (const param of pathParams) {
const paramName = param.slice(1, -1);
query[paramName] = "[Path Parameter: " + paramName + "]"; // Placeholder
}
}
// Parse query parameters (if any)
// TODO: Implement logic to parse actual query parameters from request
return { headers, body, query };
}
function parseSchema(schema, parentPath, targetObj) {
if (schema.type === "object") {
for (const [key, value] of Object.entries(schema.properties)) {
const fullPath = parentPath ? `${parentPath}.${key}` : key;
parseSchema(value, fullPath, targetObj);
}
} else if (schema.type === "array") {
// Handle arrays (simple example, can be expanded)
targetObj[parentPath] = "[Array]";
} else {
// Handle basic types (string, number, etc.)
targetObj[parentPath] = "[Placeholder]";
}
}
function flattenJson(obj, parentKey = '', result = {}) {
try {
if(typeof obj === 'string') obj = JSON.parse(obj)
} catch (error) {
// console.log("this is the error", error)
return {}
}
// console.log("this is the object", obj)
for (const [key, value] of Object.entries(obj)) {
const newKey = parentKey ? `${parentKey}.${key}` : key;
if (value && typeof value === 'object' && !Array.isArray(value)) {
// Recursively flatten for nested objects
flattenJson(value, newKey, result);
} else {
// Set the key in our result object to the value's type or placeholder
if(newKey.includes(".")) {
let splitKey = newKey.split(".")[0].trim()
result[splitKey] = typeof value === 'string' ? value : typeof value;
}
else { result[newKey] = typeof value === 'string' ? value : typeof value}
}
}
return result;
}
function findMatchingItem(items, metadata) {
// Check if items is not an array or is empty
if (!Array.isArray(items) || items.length === 0) {
return null;
}
for (const item of items) {
// Check if the item has a request and matches the metadata
if (item?.request?.url?.path && metadata?.api?.path) {
const pathMatches = `/${item.request.url.path.join("/")}` === metadata.api.path.replace(/{(\w+)}/g, ":$1");
const methodMatches = item.request.method.toLowerCase() === metadata.api.method.toLowerCase();
if (pathMatches && methodMatches) {
return item;
}
}
// If the current item has nested items, search recursively
if (item.item) {
// console.log("item.item", item.item)
const foundItem = findMatchingItem(item.item, metadata);
if (foundItem) {
return foundItem;
}
}
}
let justUrls = items.map(item => {
if(item?.request?.url?.path) {
return `/${item.request.url.path.join("/")}`
} else {
return null
}
})
// console.log("this is justUrls", justUrls)
// console.log("this is metadata", metadata.api.path)
// Return null if no matching item is found
return null;
}
function generatePostmanItem(item, metadata) {
try {
const yamlData = fs.readFileSync(`${item}`, "utf8");
let conversionResult;
let errorOccurred = false;
Converter.convert(
{ type: "string", data: yamlData },
{},
(err, result) => {
if (err) {
console.error(err);
errorOccurred = true;
} else {
conversionResult = result;
}
}
);
if (errorOccurred || !conversionResult) {
return ""; // Return an empty string in case of error
}
let apiItems = conversionResult.output[0].data.item
// console.log("this is the api items", apiItems)
// return
let flatItems = []
for(let apiItem of apiItems) {
// console.log("this is the api item", apiItem)
if(apiItem?.item?.length) flatItems = [...flatItems, ...apiItem.item]
}
let finalItem = findMatchingItem(flatItems, metadata);
// console.log("finalItem", finalItem != undefined)
// console.log("finalItem", finalItem)
metadata.postmanItem = finalItem
const template = generateTemplate(metadata.postmanItem, metadata);
return template
// if(metadata.postmanItem) fs.writeFileSync("output.json", JSON.stringify(metadata, null, 2))
// return JSON.stringify(metadata, null, 2);
} catch (err) {
console.error(err);
return ""; // Return an empty string in case of error
}
}
function handleQuery(url) {
// console.log("this is the url query", url)
if(!url.query) return {}
let queryJson = {}
for (let queryItem of url?.query) {
queryJson[queryItem.key] = queryItem
}
// console.log("this is the", queryJson)
return queryJson
}
function handleHeaders(headers) {
if(!headers) return {}
let headerJson = {}
for (let header of headers) {
headerJson[header.key] = header
}
// console.log("this is the", headerJson )
return headerJson
}
function handleMetadataBody(bodyJson, decodedJSON) {
try {
if(!decodedJSON) return bodyJson
if (!decodedJSON["application/json"]?.schema) return bodyJson
let schema = decodedJSON["application/json"].schema;
let propertiesSchemaKeys = Object.keys(schema);
let propertiesItem;
if(schema.properties) {
propertiesItem = schema
} else if(schema.items) {
propertiesItem = schema.items
} else {
for (let i = 0; i < propertiesSchemaKeys.length; i++) {
let key = propertiesSchemaKeys[i];
let value = schema[key].find(
(item) => item.properties != undefined
);
if (value) propertiesItem = value;
}
}
let { properties } = propertiesItem;
// let descriptions = [];
for (let [key, value] of Object.entries(properties)) {
bodyJson[key] = {...value, type: bodyJson[key] }
}
return bodyJson
} catch(e) {
console.error(e)
return bodyJson
}
}
function generateTemplate(data, metadata) {
try {
if(!data) return ""
// console.log(data)
let bodyJsonPlacehoder;
if(data?.request?.body?.raw) {
bodyJsonPlacehoder = flattenJson(data?.request?.body?.raw)
} else {
bodyJsonPlacehoder = {}
}
let bodyJson = bodyJsonPlacehoder || {}
if(Object.keys(bodyJson).length > 0) bodyJson = handleMetadataBody(bodyJson, metadata?.api?.requestBody?.content)
var bodyData = JSON.stringify(bodyJson);
let query = handleQuery(data?.request?.url)
let headersData = handleHeaders(data?.request?.header)
let url = JSON.stringify(query|| {})
let headers = JSON.stringify(headersData|| {})
let fullMetadataBody = JSON.stringify(metadata?.api?.requestBody || {})
var encodedBodyData = Buffer.from(bodyData).toString('base64');
var encodedUrlData = Buffer.from(url).toString('base64');
var encodedHeadersData = Buffer.from(headers).toString('base64');
var encodedMetadata = Buffer.from(fullMetadataBody).toString('base64')
return `
import ApiTabs from "@theme/ApiTabs";
import DiscriminatorTabs from "@theme/DiscriminatorTabs";
import MethodEndpoint from "@theme/ApiExplorer/MethodEndpoint";
import SecuritySchemes from "@theme/ApiExplorer/SecuritySchemes";
import MimeTabs from "@theme/MimeTabs";
import ParamsItem from "@theme/ParamsItem";
import ResponseSamples from "@theme/ResponseSamples";
import SchemaItem from "@theme/SchemaItem";
import SchemaTabs from "@theme/SchemaTabs";
import JsonToTable from '@site/src/components/JsonToTable';
import BodyTable from '@site/src/components/BodyTable';
import QueryTable from '@site/src/components/QueryTable';
import HeadersTable from '@site/src/components/HeadersTable';
import DisplayJson from '@site/src/components/DisplayJson';
import DisplayEndpoint from '@site/src/components/DisplayEndpoint';
<BodyTable title="body" data="${encodedBodyData}" />
<DisplayJson title="Whole Request" data="${encodedMetadata}" />
`;
} catch(e) {
console.error(e)
}
}
const apiConfig = {
petstore: {
// the <id> referenced when running CLI commands
specPath: "tdocxcollection.yml", // path to OpenAPI spec, URLs supported
outputDir: "docs/api/turbodocx", // output directory for generated files
sidebarOptions: {
// optional, instructs plugin to generate sidebar.js
groupPathsBy: "tag", // group sidebar items by operation "tag"
},
markdownGenerators: {
createApiPageMD: (metadata) => {
return importer.generateTempates("./tdocxcollection.yml", metadata, {postmanCollectionPath: "./tdocxpostman.json"})
// console.log("metadata", metadata);
}
}
},
};
module.exports = {
config: apiConfig,
};