@protocolnebula/ts-openapi-generator
Version:
Build API and models from Swagger/OpenAPI to use in any project type
156 lines • 6.34 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const enum_model_1 = require("../../models/enum.model");
const case_1 = require("case");
const Casual = require("casual");
const path_1 = require("path");
const model_model_1 = require("../../models/model.model");
const files_util_1 = require("../../utils/files.util");
const BINDING_REGEX = /{(.+)}/gi;
const BINDING_DB = /[^A-Za-z0-9_]/gi;
class JsonServerGenerator {
constructor() {
this.jsonDatabase = {};
this.customRoutes = {};
}
generate() {
return __awaiter(this, void 0, void 0, function* () {
console.group('');
console.log('Generating with JSON Server');
this.generateResources();
console.debug('GENERATED DB:');
console.debug(this.jsonDatabase);
this.writeFiles();
console.groupEnd();
});
}
fixURLBindings(url) {
const newURL = url.replace(BINDING_REGEX, ':$1');
console.debug('Fix bindings:', url, '->', newURL);
return newURL;
}
generateDatabaseKey(url) {
const dbKey = url.replace(BINDING_REGEX, '$1').replace(BINDING_DB, '_');
console.debug('Creating DB KEY:', dbKey);
return dbKey;
}
generateResources() {
// Avoid duplicated APIs (not supported by json-server without effort)
const generatedPaths = new Set();
for (const api of this.store.apis.apis) {
console.log(api.verb.toUpperCase(), api.url);
console.group();
const parsedURL = this.fixURLBindings(api.url);
try {
if (generatedPaths.has(parsedURL)) {
console.log('Skipped because already exist');
}
else if (!this.isResponseMappeable(api)) {
console.log('Skipped because response is not compatible');
}
else {
generatedPaths.add(parsedURL);
const dbKey = this.generateDatabaseKey(api.url);
this.customRoutes[parsedURL] = `/${dbKey}`;
this.generateDB(dbKey, api);
}
}
catch (ex) {
console.log('Skipped due:', ex);
}
console.groupEnd();
}
}
isResponseMappeable(api) {
var _a;
return (_a = api.response) === null || _a === void 0 ? void 0 : _a.typeNotPrimitive;
}
generateDB(dbKey, api) {
const response = api.response;
const responseData = this.generateFakeData(response);
this.jsonDatabase[dbKey] = responseData;
}
generateFakeData(modelAttribute) {
var _a;
const model = this.store.models.getByUri(modelAttribute.typeURI);
const data = {};
if (model instanceof model_model_1.ModelModel) {
for (const attribute of model.attributes) {
console.debug('Reading attribute:', attribute.name);
// console.group();
data[attribute.name] = this.generateValueFor(attribute);
// console.groupEnd();
}
}
else if (model instanceof enum_model_1.EnumModel) {
const rnd = Math.floor(Math.random() * (((_a = model.values) === null || _a === void 0 ? void 0 : _a.length) - 1));
return model.values[rnd];
}
return data;
}
generateValueFor(attribute) {
const getData = () => {
return attribute.typeIsPrimitive
? this.randomValue(attribute)
: this.generateFakeData(attribute);
};
let response;
if (attribute.isArray) {
for (let level = 0; level < attribute.arrayLevels; level++) {
// Create an array with the value repeated
if (!response) {
response = [getData(), getData(), getData()];
}
else {
response = [response, response];
}
}
}
else {
response = getData();
}
console.debug('Generated response:', response);
return response;
}
randomValue(attribute) {
if (attribute.default)
return attribute.default;
if (attribute.example)
return attribute.example;
// Try to generate from Casual
const keysToFindCasual = [attribute.name, attribute.description];
for (const key of keysToFindCasual) {
const generated = Casual[(0, case_1.lower)(key, '_', true)];
if (generated) {
console.debug(key, 'found in casual:', generated);
return generated;
}
}
switch (attribute.typeURI) {
case 'number':
case 'integer':
return Casual.integer(0, 100);
case 'boolean':
return Casual.boolean;
default:
return Casual['word'];
}
}
writeFiles() {
(0, files_util_1.makeDir)(this.config.mock.output);
(0, files_util_1.copyDir)((0, path_1.resolve)(__dirname, 'assets'), this.config.mock.output, !this.config.mock.partial);
(0, files_util_1.generateFileSync)((0, path_1.resolve)(this.config.mock.output, 'db.json'), JSON.stringify(this.jsonDatabase, null, 2));
(0, files_util_1.generateFileSync)((0, path_1.resolve)(this.config.mock.output, 'routes.json'), JSON.stringify(this.customRoutes, null, 2));
}
}
exports.default = JsonServerGenerator;
//# sourceMappingURL=index.js.map