forked from 92shreyansh/ondc-mock-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
344 lines (321 loc) · 10.3 KB
/
app.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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
const express = require("express");
const log = require("./utils/logger");
const app = express();
var https = require('https');
const config = require("./utils/config.js");
const router = require("./routes/route");
const $RefParser = require("json-schema-ref-parser");
const fs = require("fs");
const Handlebars = require("handlebars");
const yaml = require("js-yaml");
const { Collection, Item, Header } = require("postman-collection");
const baseTemplate = "./yaml-templates/baseTemplate.yaml";
const buildYamlFile = "./build/build.yaml";
const baseDefault = "./yaml-templates/baseDefault.yaml";
const exampleConfig = "./yaml-templates/exampleConfig.yaml";
const {
SUB_INSTRUCTION_FOLDERS,
template_paths,
allowedAttributes,
} = require("./utils/constants");
const args = process.argv.slice(2);
var configFile = args[0];
if (!configFile || configFile == "") {
configFile = "./config.yaml";
}
const matchText = 'form/'
async function baseYMLFile(file) {
try {
const schema = await $RefParser.dereference(file);
return schema;
} catch (error) {
console.error("Error parsing schema:", error);
}
}
//read the build.yaml file
createInstructionSet(buildYamlFile);
async function generateYaml(path, data, isJSON) {
try{
if (typeof data === "string" || isJSON) {
if (isJSON) {
data = JSON.stringify(data);
}
return fs.writeFileSync(path, data);
}
fs.writeFileSync(path, yaml.dump(data));
}catch(error){
console.log('Error[generateYaml]', error)
}
}
async function addHandleBars(path, examples) {
for (let paths of Object.keys(examples)) {
//create dynamic template for context for now
if (paths === "context") {
for (let attribs of Object.keys(examples[paths])) {
if (allowedAttributes.hasOwnProperty(attribs)) {
examples[paths][attribs] = `{{${allowedAttributes[attribs]}}}`;
}
}
}
}
generateYaml(path, examples);
}
async function traverseExamples(
exampleSet,
folderRef,
templateFile,
generateCollection
) {
let paths = {};
let postmanCollection = new Collection({
info: {
name: "Mock Server API",
},
item: [],
});
for (let example of Object.keys(exampleSet)) {
const { examples } = exampleSet[example];
let path = `${folderRef}/${example}.yaml`;
const isForm = example.match(matchText);
//creating paths for on-demand.yaml here
if (templateFile) {
if(isForm){
example = example.replace(/\//g, '_');
}
let pathObject = { [example]: "" };
const baseObject = {
schema: {
$ref: `${folderPath.substring()}/schema/${example}.yaml`,
//$ref: `${__dirname}/${folderPath.substring()}/schema/${example}.yaml`,
},
callbacks: {
//$ref: `${__dirname}/${folderPath.substring()}/${example}.yaml`,
$ref: `${folderPath.substring()}/${example}.yaml`,
},
};
//for forms schema is not required in root config file.
if(isForm){
delete baseObject.schema
}
pathObject[example] = baseObject;
paths = { ...paths, ...pathObject };
} else {
if(isForm){
const replacedString = example.replace(/\//g, '_');
path = `${folderRef}/${replacedString}.yaml`;
}
//read payloads & create postman collection
if (generateCollection) {
buildCollectionItems = await createCollectionItem(
example,
examples[0]?.value,
method = example.match(matchText)? "GET": "POST"
);
postmanCollection.items.add(postmanRequest);
}
addHandleBars(path, examples[0]?.value);
//generateYaml(path, examples[0]?.value);
}
}
if (postmanCollection && generateCollection) {
generatePostmanCollecion(postmanCollection, generateCollection);
}
//creating on-demand.yaml here
if (Object.keys(paths)?.length) {
let readConfigTemplate = fs.readFileSync(templateFile, "utf-8");
let template = Handlebars.compile(readConfigTemplate);
const result = template({ type: "BAP/BPP" });
readConfigTemplate = yaml.load(result);
readConfigTemplate.path = paths;
generateYaml(folderRef, readConfigTemplate);
}
}
async function traverseSchema(exampleSet, folderRef, type, templateSchema, formsData) {
for (let schema of Object.keys(formsData)) {
let schemas;
schema = `/${schema}`
const isFormFound = schema.match(matchText);
if((type === "template" || !type) && isFormFound) {
continue
}
if(!isFormFound){
schemas =
exampleSet[schema]["post"]["requestBody"]["content"]["application/json"][
"schema"
];
}
let path;
let removeExtraChar = schema.substring(1);
if(isFormFound){
//convert file name from form/personal-info to form_personal-info
const replacedString = removeExtraChar.replace(/\//g, '_');
path = `${folderRef}/${replacedString}`;
}else{
path = `${folderRef}/${schema}`;
}
if (type) {
const readTemplateFile = fs.readFileSync(templateSchema, "utf-8");
let template = Handlebars.compile(readTemplateFile);
let data = {};
if (template_paths.hasOwnProperty(removeExtraChar) || isFormFound) {
if (type === "default") {
data.callback = `${template_paths[removeExtraChar]}`;
if(isFormFound){
removeExtraChar = removeExtraChar.replace(/\//g, '_');
}
data.payload = isFormFound ? `./payloads/${removeExtraChar}.yaml`:
template_paths[removeExtraChar]
? `./template/${template_paths[removeExtraChar]}.yaml`
: "";
} else {
data.ref = `../payloads/${removeExtraChar}.yaml`;
}
schemas = template(data);
generateYaml(`${path}.yaml`, schemas);
}
} else {
generateYaml(`${path}.yaml`, schemas);
}
}
}
async function createCollectionItem(requestName, requestPayload, method) {
return (postmanRequest = new Item({
name: `${requestName}`,
request: {
header: createRequestHeader(),
url: `https://localhost:5500/${requestName}`,
method: method,
body: {
mode: "raw",
raw: JSON.stringify(requestPayload),
},
auth: null,
},
}));
}
function createRequestHeader() {
// This string will be parsed to create header
const rawHeaderString =
"Authorization:\nContent-Type:application/json\ncache-control:no-cache\n";
// Parsing string to postman compatible format
const rawHeaders = Header.parse(rawHeaderString);
// Generate headers
return rawHeaders.map((h) => new Header(h));
}
async function generatePostmanCollecion(postmanCollection, generateCollection) {
const collectionJSON = postmanCollection.toJSON();
try {
fs.writeFileSync(
`${generateCollection}_collection.json`,
JSON.stringify(collectionJSON)
);
} catch (error) {
console.log("Error creating postman collection", error);
}
}
var folderPath;
async function createInstructionSet(file) {
try {
if (args[0]) {
const path = args[0];
const file = `./${path}/${path}.yaml`;
startUp(file);
}
else{
const buildFile = await baseYMLFile(file);
const examples = buildFile["x-examples"];
const paths = buildFile["paths"];
//check entered build.yaml has on-demand exist or not
for (const instuctionSet of Object.keys(examples)) {
const { example_set: exampleSet } = examples[instuctionSet];
folderPath = `./${instuctionSet}`;
//remove previous directory on every run
fs.rmSync(folderPath, { recursive: true, force: true });
fs.mkdirSync(folderPath, {
recursive: true,
});
for (let path = 0; path < 6; path++) {
if (path < 4) {
fs.mkdirSync(`${folderPath}/${SUB_INSTRUCTION_FOLDERS[path]}`);
}
if (path === 0) {
//payloads
const generateCollection = instuctionSet;
await traverseExamples(
exampleSet,
`${folderPath}/${SUB_INSTRUCTION_FOLDERS[path]}`,
null,
generateCollection
);
} else if (path === 1) {
//operations
const baseOperations = "./yaml-templates/baseOperations.yaml";
const readOperationsTemplate = fs.readFileSync(
baseOperations,
"utf-8"
);
generateYaml(
`${folderPath}/${SUB_INSTRUCTION_FOLDERS[path]}/req_body.yaml`,
readOperationsTemplate
);
} else if (path === 2) {
//template floder
await traverseSchema(
paths,
`${folderPath}/${SUB_INSTRUCTION_FOLDERS[path]}`,
"template",
baseTemplate,
exampleSet
);
} else if (path === 3) {
//schema folder
await traverseSchema(
paths,
`${folderPath}/${SUB_INSTRUCTION_FOLDERS[path]}`,
null,
null,
exampleSet
);
} else if (path === 4) {
//config file
await traverseExamples(
exampleSet,
`${folderPath}/${instuctionSet}.yaml`,
exampleConfig
);
} else {
//creating files at on-demand root with callback & payload
await traverseSchema(paths, `${folderPath}`, "default", baseDefault, exampleSet);
}
}
console.log("yaml generated from build.yaml")
//un-comment if server has to run from same instruction set
// if (configFile === instuctionSet) {
// const file = `${folderPath}/${configFile}.yaml`;
// startUp(file);
// }
}
}
} catch (error) {
console.log("Error in createInstructionSet()", error);
}
}
//After instuctionSet completion, read response here
async function startUp(file) {
await config.loadConfig(file);
const server = config.getServer();
var options = {
key: fs.readFileSync('./client-key.pem'),
cert: fs.readFileSync('./client-cert.pem')
};
app.use(express.json());
const logger = log.init();
https.createServer(options, app).listen(server.port, () => {
logger.info(`This app is running on port number : ${server.port}`);
});
// app.listen(server.port, () => {
// logger.info(`This app is running on port number : ${server.port}`);
// });
app.use(router);
}
// startUp();