very-express 0.0.11 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/.env +2 -1
  2. package/.eslintrc.json +37 -0
  3. package/dist/cli.js +36 -33
  4. package/dist/generators/controller.template.d.ts +5 -4
  5. package/dist/generators/controller.template.js +191 -131
  6. package/dist/generators/controllers.generator.d.ts +6 -1
  7. package/dist/generators/controllers.generator.js +99 -77
  8. package/dist/generators/index.d.ts +3 -3
  9. package/dist/generators/openapi.generator.d.ts +5 -1
  10. package/dist/generators/openapi.generator.js +125 -121
  11. package/dist/generators/packageJson.generator.js +5 -12
  12. package/dist/generators/routes.generator.d.ts +10 -5
  13. package/dist/generators/routes.generator.js +6 -7
  14. package/dist/generators/routes.template.d.ts +4 -5
  15. package/dist/generators/routes.template.js +49 -27
  16. package/dist/generators/server.generator.d.ts +1 -1
  17. package/dist/generators/server.generator.js +9 -13
  18. package/dist/generators/server.template.d.ts +1 -2
  19. package/dist/generators/server.template.js +24 -25
  20. package/dist/index.d.ts +2 -2
  21. package/dist/index.js +45 -45
  22. package/dist/preprocess/jsonschemaFormat.d.ts +2 -0
  23. package/dist/preprocess/jsonschemaFormat.js +94 -0
  24. package/dist/templates/root/package.json +7 -4
  25. package/dist/templates/utils/common.gen.ts +42 -11
  26. package/dist/test.d.ts +1 -0
  27. package/dist/test.js +10 -0
  28. package/dist/types/controller.d.ts +0 -0
  29. package/dist/types/controller.js +1 -0
  30. package/dist/types/openapi.d.ts +21 -18
  31. package/dist/types/openapi.js +0 -24
  32. package/dist/types/types.d.ts +36 -21
  33. package/dist/types/types.js +3 -13
  34. package/dist/utils/common.d.ts +8 -6
  35. package/dist/utils/common.js +81 -35
  36. package/dist/utils/log.d.ts +1 -1
  37. package/dist/utils/log.js +5 -5
  38. package/package.json +60 -56
  39. package/vex.config.json +7 -0
@@ -30,126 +30,148 @@ exports.compile = void 0;
30
30
  const fs_1 = __importDefault(require("fs"));
31
31
  const js_yaml_1 = __importDefault(require("js-yaml"));
32
32
  const controller_template_1 = __importDefault(require("./controller.template"));
33
- const types = __importStar(require("../types/types"));
34
33
  const log_1 = __importDefault(require("../utils/log"));
35
- function compile(openapiPath, controllerToModelDir, outDir, options) {
36
- const file = fs_1.default.readFileSync(openapiPath, 'utf8');
34
+ const utils = __importStar(require("../utils/common"));
35
+ const types = __importStar(require("../types/types"));
36
+ function compile(options) {
37
+ const file = fs_1.default.readFileSync(options.compilerOptions.openapiDir + "/" + options.openapiFile, "utf8");
38
+ const controllerToModelBasePath = utils.relativePath(options.controllerOutDir, options.modelDir);
37
39
  const openApi = js_yaml_1.default.load(file);
38
40
  const endpointsValidator = {};
39
- let writtedEndpoint = [];
41
+ const writtedEndpoint = [];
40
42
  Object.keys(openApi.paths).forEach((endpoint) => {
41
43
  endpointsValidator[endpoint] = {};
42
- log_1.default.process(`Controller : ${openapiPath} > ${endpoint}`);
43
- Object.keys(openApi.paths[endpoint]).forEach((method) => {
44
- if (!Object.values(types.method).includes(method))
44
+ log_1.default.process(`Controller : ${options.compilerOptions.openapiDir} > ${endpoint}`);
45
+ Object.keys(openApi.paths[endpoint]).forEach((httpMethod) => {
46
+ if (!Object.values(types.httpMethodArr).includes(httpMethod))
45
47
  return;
46
- let methodEnum = method;
47
- let validators = [];
48
- validators = buildParamValidator(endpoint, methodEnum, openApi);
49
- validators = validators.concat(buildRequestBodyValidator(endpoint, methodEnum, openApi));
50
- endpointsValidator[endpoint][method] = validators;
48
+ const methodEnum = httpMethod;
49
+ const validators = Object.assign(buildParamValidator(endpoint, methodEnum, openApi, options.compilerOptions), buildBodyValidator(endpoint, methodEnum, openApi));
50
+ endpointsValidator[endpoint][httpMethod] = validators;
51
51
  });
52
52
  });
53
53
  Object.keys(openApi.paths).forEach((endpoint) => {
54
- const interfaceName = openApi.paths[endpoint].summary;
55
- const endpointFormatted = endpoint.replace('/{id}', '').toLowerCase();
56
- if (writtedEndpoint.includes(endpointFormatted)) {
54
+ const collectionName = openApi.paths[endpoint]["x-collection"];
55
+ const interfaceName = openApi.paths[endpoint]["x-interface"];
56
+ const endpointFormatted = endpoint.replace("/{id}", "").toLowerCase();
57
+ if (collectionName === undefined) {
58
+ log_1.default.error(`"x-collection" not found in openapi spec's path "${endpoint}"\n - opanapi source: ${options.compilerOptions.openapiDir}`);
57
59
  return;
58
60
  }
59
- else {
60
- writtedEndpoint.push(endpointFormatted);
61
+ else if (interfaceName === undefined) {
62
+ log_1.default.error(`"x-interface" not found in openapi spec's path "${endpoint}"\n - opanapi source: ${options.compilerOptions.openapiDir}`);
63
+ return;
61
64
  }
62
- ;
63
- const outPath = `${outDir}/${interfaceName}Controller.gen.ts`;
64
- const outPathNoGen = `${outDir}/${interfaceName}Controller.nogen.ts`;
65
- const controllerToModelPath = `${controllerToModelDir}/${interfaceName}Model.gen`;
66
- log_1.default.writing(`Controller : ${outPath}`);
67
- if (!fs_1.default.existsSync(outPathNoGen)) {
68
- fs_1.default.writeFileSync(outPath, (0, controller_template_1.default)({
69
- endpoint: endpoint,
70
- modelPath: controllerToModelPath,
71
- interfaceName: interfaceName,
72
- validator: endpointsValidator,
73
- options: options,
74
- }));
65
+ else if (writtedEndpoint.includes(endpointFormatted)) {
66
+ return;
67
+ }
68
+ else {
69
+ const outPath = `${options.controllerOutDir}/${interfaceName}Controller.gen.ts`;
70
+ const outPathNoGen = `${options.controllerOutDir}/${interfaceName}Controller.nogen.ts`;
71
+ const controllerToModelPath = `${controllerToModelBasePath}/${interfaceName}Model.gen`;
72
+ if (!fs_1.default.existsSync(outPathNoGen)) {
73
+ log_1.default.writing(`Controller : ${outPath}`);
74
+ writtedEndpoint.push(endpointFormatted);
75
+ fs_1.default.writeFileSync(outPath, (0, controller_template_1.default)({
76
+ endpoint: endpoint,
77
+ modelPath: controllerToModelPath,
78
+ interfaceName: interfaceName,
79
+ validators: endpointsValidator,
80
+ compilerOptions: options.compilerOptions,
81
+ }));
82
+ }
75
83
  }
76
- ;
77
84
  });
78
85
  }
79
86
  exports.compile = compile;
80
- ;
81
- function buildParamValidator(endpoint, method, openapi) {
82
- let validators = [];
83
- openapi.paths[endpoint][method].parameters.forEach((parameter) => {
84
- validators = validators.concat(processSchema(parameter.name, parameter, undefined));
87
+ function buildParamValidator(endpoint, httpMethod, openapi, compilerOptions) {
88
+ const validators = {};
89
+ openapi.paths[endpoint][httpMethod].parameters.forEach((parameter) => {
90
+ if (!compilerOptions.use_id && parameter.name === "_id") {
91
+ return;
92
+ }
93
+ Object.assign(validators, processSchema({
94
+ fieldName: parameter.name,
95
+ required: parameter.required,
96
+ param: parameter,
97
+ }));
85
98
  });
86
99
  return validators;
87
100
  }
88
- ;
89
- function buildRequestBodyValidator(endpoint, method, openapi) {
90
- var _a, _b, _c;
91
- let validators = [];
92
- const referencePath = (_c = (_b = (_a = openapi.paths[endpoint][method]) === null || _a === void 0 ? void 0 : _a.requestBody) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c['application/json'].schema.$ref;
93
- const reference = referencePath ? referencePath.split('/').pop() : undefined;
101
+ function buildBodyValidator(endpoint, httpMethod, openapi) {
102
+ var _a, _b, _c, _d;
103
+ const validators = {};
104
+ const referencePath = (_c = (_b = (_a = openapi.paths[endpoint][httpMethod]) === null || _a === void 0 ? void 0 : _a.requestBody) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c["application/json"].schema.$ref;
105
+ const reference = referencePath ? referencePath.split("/").pop() : undefined;
94
106
  const components = reference ? openapi.components.schemas[reference] : undefined;
95
107
  if (components !== undefined) {
96
- for (let key in components.properties) {
97
- validators = validators.concat(processSchema(key, undefined, components.properties[key]));
108
+ for (const key in components.properties) {
109
+ Object.assign(validators, processSchema({
110
+ fieldName: key,
111
+ body: components.properties[key],
112
+ required: ((_d = components.required) === null || _d === void 0 ? void 0 : _d.includes(key)) || components.properties[key].required,
113
+ }));
98
114
  }
99
- ;
100
115
  }
101
116
  return validators;
102
117
  }
103
- function processSchema(fieldName, paramFields, bodyFields) {
104
- var _a, _b, _c, _d;
105
- let validators = [];
106
- const useBody = bodyFields !== undefined && paramFields == undefined;
107
- const checkOn = useBody ? 'body' : 'check';
108
- const type = useBody ? bodyFields === null || bodyFields === void 0 ? void 0 : bodyFields.type : paramFields === null || paramFields === void 0 ? void 0 : paramFields.schema.type;
109
- const required = (paramFields === null || paramFields === void 0 ? void 0 : paramFields.required) ? '.exists()' : '.optional()';
110
- const enumValidator = useBody && (bodyFields === null || bodyFields === void 0 ? void 0 : bodyFields.enum) ? `.isIn(${JSON.stringify(bodyFields.enum)})` :
111
- !useBody && (paramFields === null || paramFields === void 0 ? void 0 : paramFields.schema.enum) ? `.isIn(${JSON.stringify(paramFields.schema.enum)})` :
112
- '';
113
- const typeValidatorOption = JSON.stringify(useBody && bodyFields ? {
114
- min: bodyFields.minLength || bodyFields.minimum,
115
- max: bodyFields.maxLength || bodyFields.maximum,
116
- } :
117
- !useBody && paramFields ? {
118
- min: ((_a = paramFields.schema) === null || _a === void 0 ? void 0 : _a.minLength) || ((_b = paramFields.schema) === null || _b === void 0 ? void 0 : _b.minimum),
119
- max: ((_c = paramFields.schema) === null || _c === void 0 ? void 0 : _c.maxLength) || ((_d = paramFields.schema) === null || _d === void 0 ? void 0 : _d.maximum),
120
- } :
121
- undefined);
122
- const typeValidator = typeValidatorOption !== '{}' ? typeValidatorOption : undefined;
118
+ function processSchema(options) {
119
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1;
120
+ const validators = {
121
+ [options.fieldName]: {
122
+ in: options.param ? "params" : options.body ? "body" : [],
123
+ optional: !options.required ? { options: { values: "falsy", checkFalsy: true } } : false,
124
+ notEmpty: true,
125
+ },
126
+ };
127
+ const validatorParam = validators[options.fieldName];
128
+ const useBody = options.body !== undefined && options.param == undefined;
129
+ const type = useBody ? (_a = options.body) === null || _a === void 0 ? void 0 : _a.type : (_b = options.param) === null || _b === void 0 ? void 0 : _b.schema.type;
130
+ const useEnum = (_e = (_d = (_c = options.param) === null || _c === void 0 ? void 0 : _c.schema) === null || _d === void 0 ? void 0 : _d.enum) !== null && _e !== void 0 ? _e : (_f = options.body) === null || _f === void 0 ? void 0 : _f.enum;
131
+ const range = {
132
+ min: (_p = (_m = (_j = (_h = (_g = options.param) === null || _g === void 0 ? void 0 : _g.schema) === null || _h === void 0 ? void 0 : _h.minLength) !== null && _j !== void 0 ? _j : (_l = (_k = options.param) === null || _k === void 0 ? void 0 : _k.schema) === null || _l === void 0 ? void 0 : _l.minimum) !== null && _m !== void 0 ? _m : (_o = options.body) === null || _o === void 0 ? void 0 : _o.minLength) !== null && _p !== void 0 ? _p : (_q = options.body) === null || _q === void 0 ? void 0 : _q.minimum,
133
+ max: (_y = (_w = (_t = (_s = (_r = options.param) === null || _r === void 0 ? void 0 : _r.schema) === null || _s === void 0 ? void 0 : _s.maxLength) !== null && _t !== void 0 ? _t : (_v = (_u = options.param) === null || _u === void 0 ? void 0 : _u.schema) === null || _v === void 0 ? void 0 : _v.maximum) !== null && _w !== void 0 ? _w : (_x = options.body) === null || _x === void 0 ? void 0 : _x.maxLength) !== null && _y !== void 0 ? _y : (_z = options.body) === null || _z === void 0 ? void 0 : _z.maximum,
134
+ };
135
+ const rangeValidator = range.min && range.max ? { options: range } : undefined;
123
136
  switch (type) {
124
137
  case "string":
125
- validators.push(`${checkOn}("${fieldName}")${required}.isString()${typeValidator !== undefined ? `.isLength(${typeValidator})` : ''}${enumValidator}`);
138
+ validatorParam.isString = true;
139
+ if (range.min && range.max) {
140
+ validatorParam.isLength = { options: range };
141
+ }
142
+ if (useEnum) {
143
+ validatorParam.isEmpty = false;
144
+ validatorParam.isIn = {
145
+ options: useEnum,
146
+ };
147
+ }
126
148
  break;
127
149
  case "integer":
128
- validators.push(`${checkOn}("${fieldName}")${required}.isInt(${typeValidator})`);
150
+ validatorParam.isInt = rangeValidator;
129
151
  break;
130
152
  case "float":
131
- validators.push(`${checkOn}("${fieldName}")${required}.isFloat(${typeValidator})`);
153
+ validatorParam.isFloat = rangeValidator;
132
154
  break;
133
155
  case "number":
134
- validators.push(`${checkOn}("${fieldName}")${required}.isNumeric()`);
156
+ validatorParam.isNumeric = true;
135
157
  break;
136
158
  case "boolean":
137
- validators.push(`${checkOn}("${fieldName}")${required}.isBoolean()`);
159
+ validatorParam.isBoolean = true;
138
160
  break;
139
161
  case "array":
140
- validators.push(`${checkOn}("${fieldName}")${required}.isArray(${typeValidator})`);
162
+ validatorParam.isArray = true;
141
163
  break;
142
164
  case "object":
143
165
  if (useBody) {
144
- for (let key in bodyFields === null || bodyFields === void 0 ? void 0 : bodyFields.properties) {
145
- validators = validators.concat(processSchema(fieldName + '.' + key, undefined, bodyFields.properties[key]));
166
+ for (const key in (_0 = options.body) === null || _0 === void 0 ? void 0 : _0.properties) {
167
+ Object.assign(validators, processSchema({
168
+ fieldName: options.fieldName + "." + key,
169
+ body: options.body.properties[key],
170
+ required: (_1 = options.body.required) === null || _1 === void 0 ? void 0 : _1.includes(key),
171
+ }));
146
172
  }
147
- ;
148
173
  }
149
- ;
150
174
  break;
151
175
  }
152
- ;
153
176
  return validators;
154
177
  }
155
- ;
@@ -1,6 +1,6 @@
1
- import controllerTemplate from './controller.template';
2
- import routesTemplate from './routes.template';
3
- import serverTemplate from './server.template';
1
+ import controllerTemplate from "./controller.template";
2
+ import routesTemplate from "./routes.template";
3
+ import serverTemplate from "./server.template";
4
4
  declare const _default: {
5
5
  controllerTemplate: typeof controllerTemplate;
6
6
  routesTemplate: typeof routesTemplate;
@@ -1,2 +1,6 @@
1
- export declare function compile(schemaDir: string, outPath: string): void;
1
+ import * as types from "../types/types";
2
+ export declare function compile(options: {
3
+ openapiOutFileName: string;
4
+ compilerOptions: types.compilerOptions;
5
+ }): void;
2
6
  export default compile;
@@ -1,27 +1,4 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
4
  };
@@ -30,10 +7,9 @@ exports.compile = void 0;
30
7
  const json_schema_to_openapi_schema_1 = __importDefault(require("json-schema-to-openapi-schema"));
31
8
  const js_yaml_1 = __importDefault(require("js-yaml"));
32
9
  const fs_1 = __importDefault(require("fs"));
33
- const types = __importStar(require("../types/types"));
34
10
  const common_1 = __importDefault(require("../utils/common"));
35
11
  const log_1 = __importDefault(require("../utils/log"));
36
- function compile(schemaDir, outPath) {
12
+ function compile(options) {
37
13
  let openapiJson = {
38
14
  openapi: "3.0.0",
39
15
  info: {
@@ -46,168 +22,196 @@ function compile(schemaDir, outPath) {
46
22
  schemas: {},
47
23
  },
48
24
  };
49
- const files = fs_1.default.readdirSync(schemaDir);
25
+ const files = fs_1.default.readdirSync(options.compilerOptions.jsonSchemaDir);
50
26
  files.forEach((file) => {
51
- if (!file.endsWith('.json'))
27
+ if (!file.endsWith(".json"))
52
28
  return;
53
- log_1.default.process(`OpenApi : ${schemaDir + '/' + file}`);
54
- const jsonSchemaBuffer = fs_1.default.readFileSync(`${schemaDir}/${file}`);
29
+ const jsonSchemaFilePath = options.compilerOptions.jsonSchemaDir + "/" + file;
30
+ log_1.default.process(`OpenApi : ${jsonSchemaFilePath}`);
31
+ const jsonSchemaBuffer = fs_1.default.readFileSync(`${options.compilerOptions.jsonSchemaDir}/${file}`);
55
32
  const jsonSchema = JSON.parse(jsonSchemaBuffer.toString());
56
- openapiJson = jsonToOpenapiPath(openapiJson, jsonSchema);
57
- openapiJson = jsonToOpenapiComponentSchema(openapiJson, jsonSchema);
33
+ openapiJson = jsonToOpenapiPath(openapiJson, jsonSchema, { jsonSchemaFilePath: jsonSchemaFilePath });
34
+ openapiJson = jsonToOpenapiComponentSchema(openapiJson, jsonSchema, { jsonSchemaFilePath: jsonSchemaFilePath });
58
35
  });
59
36
  const validOpenApi = (0, json_schema_to_openapi_schema_1.default)(openapiJson, { version: 3.0 });
60
37
  const openapiYaml = js_yaml_1.default.dump(validOpenApi);
61
- log_1.default.writing(`OpenApi : ${outPath}`);
62
- fs_1.default.writeFileSync(outPath, openapiYaml);
38
+ const openapiOutFile = options.compilerOptions.openapiDir + options.openapiOutFileName;
39
+ log_1.default.writing(`OpenApi : ${openapiOutFile}`);
40
+ fs_1.default.writeFileSync(openapiOutFile, openapiYaml);
63
41
  }
64
42
  exports.compile = compile;
65
- ;
66
- function jsonToOpenapiPath(openapiJson, jsonSchema) {
43
+ function jsonToOpenapiPath(openapiJson, jsonSchema, additionalinfo) {
67
44
  const documentConfig = jsonSchema["x-documentConfig"];
68
45
  const lowerDocName = documentConfig.documentName.toLowerCase();
69
46
  const interfaceName = documentConfig.interfaceName;
70
47
  const properties = jsonSchema.properties;
71
- const methods = documentConfig.methods;
72
- let routes = {
73
- ['/' + lowerDocName]: {
74
- summary: interfaceName,
48
+ const routes = {
49
+ ["/" + lowerDocName]: {
50
+ "x-collection": documentConfig.documentName,
51
+ "x-interface": interfaceName,
75
52
  },
76
- ['/' + lowerDocName + '/{id}']: {
77
- summary: interfaceName,
53
+ ["/" + lowerDocName + "/{id}"]: {
54
+ "x-collection": documentConfig.documentName,
55
+ "x-interface": interfaceName,
78
56
  },
79
57
  };
80
- methods.forEach((method) => {
81
- const useId = [types.method.put, types.method.patch, types.method.delete].includes(method);
82
- const useBody = [types.method.post, types.method.put, types.method.patch].includes(method);
83
- const route = '/' + lowerDocName + (useId ? '/{id}' : '');
84
- routes[route][method] = {
85
- summary: interfaceName,
86
- operationId: method + interfaceName,
87
- tags: [lowerDocName],
88
- parameters: [],
89
- requestBody: undefined,
90
- responses: {
91
- 200: {
92
- description: 'OK',
93
- content: {
94
- 'application/json': { schema: { $ref: `#/components/schemas/${method}${interfaceName}Response` } },
95
- },
58
+ documentConfig.methods.forEach((jsonSchemaMethod) => {
59
+ const routeWithId = ["get", "put", "patch", "delete"].includes(jsonSchemaMethod);
60
+ const useBody = ["post", "put", "patch"].includes(jsonSchemaMethod);
61
+ const route = "/" + lowerDocName + (routeWithId ? "/{id}" : "");
62
+ const httpMethod = common_1.default.httpMethod(jsonSchemaMethod, additionalinfo.jsonSchemaFilePath);
63
+ const parameters = [];
64
+ let requestBody = undefined;
65
+ const successResponse = {
66
+ 200: {
67
+ description: "OK",
68
+ content: {
69
+ "application/json": { schema: { $ref: `#/components/schemas/${httpMethod}${interfaceName}Response` } },
96
70
  },
97
- 400: { description: 'Bad Request', },
98
- 401: { description: 'Unauthorized', },
99
- 403: { description: 'Forbidden', },
100
- 404: { description: 'Not Found', },
101
- 405: { description: 'Method Not Allowed', },
102
- 413: { description: 'Payload Too Large', },
103
- 429: { description: 'Too Many Requests', },
104
- 500: { description: 'Internal Server Error', },
105
- 502: { description: 'Bad Gateway', },
106
- 503: { description: 'Service Unavailable', },
107
71
  },
108
72
  };
109
- if ((useId || method == types.method.get) && properties['_id']) {
73
+ if (routeWithId && properties["_id"]) {
110
74
  const idParameter = {
111
- name: 'id',
112
- in: 'path',
113
- description: properties['_id'].description,
75
+ name: "id",
76
+ in: "path",
77
+ description: properties["_id"].description,
114
78
  required: true,
115
79
  schema: {
116
- type: properties['_id'].type,
117
- format: properties['_id'].format,
80
+ type: properties["_id"].type,
81
+ format: properties["_id"].format,
118
82
  },
119
83
  };
120
- routes[route][method].parameters = [idParameter];
121
- if (method == types.method.get) {
122
- routes[route + '/{id}'][method] = Object.assign({}, routes[route][method]);
123
- routes[route + '/{id}'][method].responses[200].content["application/json"].schema.$ref = `#/components/schemas/${method}${interfaceName}Response`;
124
- routes[route + '/{id}'][method].parameters = [idParameter];
125
- }
126
- ;
84
+ parameters.push(idParameter);
127
85
  }
128
- ;
129
- if (method == types.method.post) {
130
- routes[route][method].responses[201] = routes[route][method].responses[200];
131
- routes[route][method].responses[201].description = 'Crerated';
132
- delete routes[route][method].responses[200];
86
+ if (httpMethod == "post") {
87
+ successResponse[201] = Object.assign({}, successResponse[200]);
88
+ successResponse[201].description = "Crerated";
89
+ delete successResponse[200];
133
90
  }
134
- else if (method == types.method.delete) {
135
- delete routes[route][method].responses[200].content;
91
+ else if (httpMethod == "delete") {
92
+ delete successResponse[200].content;
136
93
  }
137
- ;
138
94
  if (useBody) {
139
- routes[route][method].requestBody = {
140
- description: `${method} ${documentConfig.documentName}`,
95
+ requestBody = {
96
+ description: `${httpMethod} ${documentConfig.documentName}`,
141
97
  required: false,
142
98
  content: {
143
- 'application/json': { schema: { $ref: `#/components/schemas/${method}${interfaceName}Body` } },
99
+ "application/json": { schema: { $ref: `#/components/schemas/${httpMethod}${interfaceName}Body` } },
144
100
  },
145
101
  };
146
102
  }
147
- ;
103
+ routes[route][httpMethod] = {
104
+ operationId: jsonSchemaMethod + interfaceName,
105
+ tags: [lowerDocName],
106
+ parameters: parameters,
107
+ requestBody: requestBody,
108
+ responses: Object.assign({
109
+ 400: { description: "Bad Request", },
110
+ 401: { description: "Unauthorized", },
111
+ 403: { description: "Forbidden", },
112
+ 404: { description: "Not Found", },
113
+ 405: { description: "Method Not Allowed", },
114
+ 413: { description: "Payload Too Large", },
115
+ 429: { description: "Too Many Requests", },
116
+ 500: { description: "Internal Server Error", },
117
+ 502: { description: "Bad Gateway", },
118
+ 503: { description: "Service Unavailable", },
119
+ }, successResponse)
120
+ };
148
121
  });
149
122
  openapiJson.paths = Object.assign(openapiJson.paths, routes);
150
123
  return openapiJson;
151
124
  }
152
- ;
153
- function jsonToOpenapiComponentSchema(openapiJson, jsonSchema) {
154
- let parameters = [];
155
- let componentSchemaPath = {};
125
+ function jsonToOpenapiComponentSchema(openapiJson, jsonSchema, additionalinfo) {
126
+ const componentSchemaPath = {};
156
127
  const documentConfig = jsonSchema["x-documentConfig"];
157
128
  const lowerDocName = documentConfig.documentName.toLowerCase();
158
129
  const interfaceName = documentConfig.interfaceName;
159
- const methods = documentConfig.methods;
160
130
  const componentSchemaResponse = {
161
- type: 'object',
162
- properties: (0, json_schema_to_openapi_schema_1.default)(common_1.default.cleanXcustomValue(jsonSchema.properties, ['index', 'unique', 'required']), { version: 3.0 }),
131
+ type: "object",
132
+ properties: (0, json_schema_to_openapi_schema_1.default)(common_1.default.cleanXcustomValue(jsonSchema.properties, ["index", "unique", "required"]), { version: 3.0 }),
163
133
  };
164
134
  const componentSchemaBody = {
165
- type: 'object',
166
- properties: (0, json_schema_to_openapi_schema_1.default)(common_1.default.cleanXcustomValue(jsonSchema.properties, ['_id', 'index', 'unique', 'required']), { version: 3.0 }),
135
+ type: "object",
136
+ properties: (0, json_schema_to_openapi_schema_1.default)(common_1.default.cleanXcustomValue(jsonSchema.properties, ["_id", "index", "unique", "required"]), { version: 3.0 }),
137
+ };
138
+ const componentSchemaBodyRequired = {
139
+ type: "object",
140
+ properties: (0, json_schema_to_openapi_schema_1.default)(common_1.default.cleanXcustomValue(jsonSchema.properties, { _id: "string", index: "boolean", unique: "boolean", required: "boolean" }), { version: 3.0 }),
141
+ required: jsonSchema.required,
167
142
  };
168
- methods.forEach((method) => {
169
- switch (method) {
170
- case types.method.delete:
143
+ documentConfig.methods.forEach((jsonSchemaMethod) => {
144
+ const httpMethod = common_1.default.httpMethod(jsonSchemaMethod, additionalinfo.jsonSchemaFilePath);
145
+ switch (jsonSchemaMethod) {
146
+ case "delete":
147
+ break;
148
+ case "get":
149
+ componentSchemaPath[httpMethod + interfaceName + "Response"] = componentSchemaResponse;
171
150
  break;
172
- case types.method.get:
173
- let parameters = [];
151
+ case "getList": {
152
+ const parameters = [];
174
153
  Object.keys(jsonSchema.properties).forEach((key) => {
175
154
  const props = jsonSchema.properties[key];
176
- if (props.type == 'object')
155
+ if (props.type == "object")
177
156
  return;
178
- let parameter = {
157
+ parameters.push({
179
158
  name: key,
180
159
  in: "query",
181
- required: props.required,
160
+ required: false,
182
161
  schema: {
183
162
  type: props.type,
184
163
  format: props.format,
164
+ "x-format": props["x-format"],
185
165
  minLength: props.minLength,
186
166
  maxLength: props.maxLength,
187
167
  minimum: props.minimum,
188
168
  maximum: props.maximum,
189
169
  enum: props.enum,
190
170
  }
191
- };
192
- parameters.push(parameter);
171
+ });
172
+ switch (props["x-format"]) {
173
+ case "minMax":
174
+ parameters.push({
175
+ name: "min_" + key,
176
+ in: "query",
177
+ required: false,
178
+ schema: {
179
+ type: "number",
180
+ }
181
+ });
182
+ parameters.push({
183
+ name: "max_" + key,
184
+ in: "query",
185
+ required: false,
186
+ schema: {
187
+ type: "number",
188
+ }
189
+ });
190
+ break;
191
+ default:
192
+ break;
193
+ }
193
194
  });
194
- openapiJson.paths['/' + lowerDocName][method].parameters = parameters;
195
- componentSchemaPath[method + interfaceName + 'Response'] = componentSchemaResponse;
196
- componentSchemaPath[method + interfaceName + 'ResponseList'] = {
197
- type: 'array',
195
+ openapiJson.paths["/" + lowerDocName][httpMethod].parameters = parameters;
196
+ componentSchemaPath[httpMethod + interfaceName + "Response"] = componentSchemaResponse;
197
+ componentSchemaPath[httpMethod + interfaceName + "ResponseList"] = {
198
+ type: "array",
198
199
  items: componentSchemaResponse,
199
200
  };
200
201
  break;
201
- case types.method.post:
202
- case types.method.put:
203
- case types.method.patch:
204
- componentSchemaPath[method + interfaceName + 'Body'] = componentSchemaBody;
205
- componentSchemaPath[method + interfaceName + 'Response'] = componentSchemaResponse;
202
+ }
203
+ case "patch":
204
+ componentSchemaPath[httpMethod + interfaceName + "Body"] = componentSchemaBody;
205
+ componentSchemaPath[httpMethod + interfaceName + "Response"] = componentSchemaResponse;
206
+ break;
207
+ case "post":
208
+ case "put":
209
+ componentSchemaPath[httpMethod + interfaceName + "Body"] = componentSchemaBodyRequired;
210
+ componentSchemaPath[httpMethod + interfaceName + "Response"] = componentSchemaResponse;
206
211
  break;
207
212
  default:
208
213
  break;
209
214
  }
210
- ;
211
215
  });
212
216
  openapiJson.components.schemas = Object.assign(openapiJson.components.schemas, componentSchemaPath);
213
217
  return openapiJson;