-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcodegen-postman.js
176 lines (160 loc) · 5.22 KB
/
codegen-postman.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
const OASNormalize = require("oas-normalize");
const fs = require("fs");
const path = require("path");
const sdk = require('postman-collection');
const postman = require('postman-code-generators');
const oas = new OASNormalize(path.resolve(__dirname, "./clarifai-postman-collection.json"), {enablePaths: true})
// Function to resolve $ref references
function resolveRef(ref, spec) {
const parts = ref.replace(/^#\//, '').split('/');
let result = spec;
for (const part of parts) {
result = result[part];
}
return result;
}
// Function to generate example data from a schema
function generateExample(schema, spec) {
if (schema.example) {
return schema.example;
}
if (schema.$ref) {
const resolvedSchema = resolveRef(schema.$ref, spec);
return generateExample(resolvedSchema, spec);
}
if (schema.type === 'object') {
const example = {};
for (const [key, property] of Object.entries(schema.properties || {})) {
example[key] = generateExample(property, spec);
}
return example;
}
if (schema.type === 'array') {
return [generateExample(schema.items, spec)];
}
if (schema.type === 'string') {
return 'string';
}
if (schema.type === 'integer') {
return 0;
}
if (schema.type === 'boolean') {
return true;
}
// Add more types as needed
return null;
}
const servers = [{
url: "https://api.clarifai.com"
}]
// Function to convert OpenAPI spec to Postman collection
function convertToPostmanCollection(openApiSpec) {
const collection = new sdk.Collection();
// Loop through paths and methods in the OpenAPI spec
for (const pathKey in openApiSpec.paths) {
for (const method in openApiSpec.paths[pathKey]) {
const endpoint = openApiSpec.paths[pathKey][method];
const request = {
method: method.toUpperCase(),
header: [{
key: "Authorization",
value: "Bearer YOUR_PERSONAL_ACCESS_TOKEN",
}, {
key: 'Accept',
value: 'application/json'
}],
url: {
raw: `${openApiSpec.servers[0].url}${pathKey}`,
host: [openApiSpec.servers[0].url],
path: pathKey.split('/').filter(Boolean),
query: []
},
body: {}
};
// Add headers
if (endpoint.parameters) {
endpoint.parameters.forEach((param) => {
if (param.in === 'header') {
request.header.push({
key: param.name,
value: param.example || '',
type: 'text'
});
}
// Add query parameters
if (param.in === 'query') {
request.url.query.push({
key: param.name,
value: param.example || ''
});
}
});
}
// Add request body
if (endpoint.requestBody) {
const content = endpoint.requestBody.content;
if (content?.['application/json']) {
const schema = content['application/json'].schema;
const example = generateExample(schema, openApiSpec);
request.body = {
mode: 'raw',
raw: JSON.stringify(example, null, 2)
};
request.header.push({
key: 'Content-Type',
value: 'application/json'
});
} else if (content?.['application/x-www-form-urlencoded']) {
const schema = content['application/x-www-form-urlencoded'].schema;
const example = generateExample(schema, openApiSpec);
request.body = {
mode: 'urlencoded',
urlencoded: Object.keys(example).map(key => ({
key: key,
value: example[key]
}))
};
request.header.push({
key: 'Content-Type',
value: 'application/x-www-form-urlencoded'
});
}
}
collection.items.add(new sdk.Item({
name: `${method.toUpperCase()} ${pathKey}`,
request: request
}));
}
}
return collection;
}
oas.validate({
convertToLatest: true,
}).then(definition => {
definition.servers = servers;
const collection = convertToPostmanCollection(definition);
collection.items.each((item) => {
const languages = [['cURL', 'cURL']];
languages.forEach(([language, variant]) => {
postman.convert(language, variant, item.request, {}, (error, snippet) => {
if (error) {
console.error('Error generating code snippet:', error);
} else {
const [method, pathKey] = item.name.split(' ', 2);
const endpoint = definition.paths?.[pathKey.toLowerCase()]?.[method.toLowerCase()];
if(endpoint) {
if (!endpoint['x-codeSamples']) {
endpoint['x-codeSamples'] = [];
}
endpoint['x-codeSamples'].push({
lang: language,
label: language.toUpperCase(),
source: snippet
});
}
}
});
});
});
fs.writeFileSync(path.resolve(__dirname, "static/api-spec/clarifai-v3.json"), JSON.stringify(definition, null, 2));
})