UNPKG

express-oven

Version:

An easy mock API generator with express.js

1,190 lines (1,067 loc) 31.9 kB
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var express = require('express'); var multer = _interopDefault(require('multer')); var lightUid = require('light-uid'); var lightJoin = _interopDefault(require('light-join')); var path = require('path'); var fs = require('fs'); var json5 = require('json5'); var merge = _interopDefault(require('deepmerge')); var Ajv = _interopDefault(require('ajv')); var DEFAULT_CONFIG_PATH = 'oven.configs.json5'; var HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete']; var isHttpMethod = function isHttpMethod(method) { return HTTP_METHODS.includes(method); }; var DEFAULT_CONFIGS = { save: false, returnEntity: true, delay: 300, handleFile: { directoryPath: 'data/uploads' }, responseModel: { paths: {} } }; var IGNORE_KEY = '#ignore'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var getNumberId = function getNumberId(data, idField) { return Math.max.apply(Math, data.map(function (item) { return item[idField]; })) + 1; }; var delay = function delay(ms) { return new Promise(function (resolve) { return setTimeout(resolve, ms); }); }; var setPropDeep = function setPropDeep(obj, prop, value) { if (!prop) { return value; } var pathArr = prop.split('.'); var finalResponse = obj != null ? obj : {}; var tempObj = finalResponse; pathArr.forEach(function (pathPart, index) { if (index === pathArr.length - 1) { tempObj[pathPart] = value; } if (!tempObj[pathPart]) { tempObj[pathPart] = {}; } tempObj = tempObj[pathPart]; }); return finalResponse; }; var getPropDeep = function getPropDeep(obj, path) { if (!path) { return obj; } if (!obj) { return undefined; } var pathArr = path.split('.'); var value = obj; for (var _iterator = _createForOfIteratorHelperLoose(pathArr), _step; !(_step = _iterator()).done;) { var pathPart = _step.value; value = value[pathPart]; if (value === undefined) { return value; } } return value; }; var createResponseBuilder = function createResponseBuilder(responseModel) { var response; return { setData: function setData(data) { response = setPropDeep(response, responseModel.paths.data, data); }, write: function write(res) { response === undefined ? res.end() : res.send(response); } }; }; var getCreateEntityHandler = function getCreateEntityHandler(methodConfigs, dataAdapterStorage) { var dataAdapter = dataAdapterStorage.getAdapter(methodConfigs.dataJsonPath); var _methodConfigs$uidFie = methodConfigs.uidField, type = _methodConfigs$uidFie.type, name = _methodConfigs$uidFie.name; return function (req, res) { try { var _extends2; var responseBuilder = createResponseBuilder(methodConfigs.responseModel); var newDataItem = _extends((_extends2 = {}, _extends2[name] = type === 'number' ? getNumberId(dataAdapter.getAll(), name) : lightUid.genUid(), _extends2), req.body, methodConfigs.extensions.withDefaultValues); dataAdapter.addOne(newDataItem, methodConfigs.save); return Promise.resolve(delay(methodConfigs.delay)).then(function () { var _ref; responseBuilder.setData(methodConfigs.returnEntity ? newDataItem : (_ref = {}, _ref[name] = newDataItem[name], _ref)); responseBuilder.write(res); }); } catch (e) { return Promise.reject(e); } }; }; var matchEntitiesByParams = function matchEntitiesByParams(params, paramMatch) { return function (entity) { return paramMatch ? Object.entries(params).every(function (_ref) { var _paramMatch$param; var param = _ref[0], value = _ref[1]; var entityKeyPath = (_paramMatch$param = paramMatch[param]) != null ? _paramMatch$param : param; if (entityKeyPath === IGNORE_KEY) { return true; } var entityValue = getPropDeep(entity, entityKeyPath); return String(entityValue) === value; }) : true; }; }; var matchEntitiesByBodyFilters = function matchEntitiesByBodyFilters(body, bodyMatch) { return function (entity) { return bodyMatch ? Object.entries(bodyMatch).every(function (_ref2) { var bodyKeyPath = _ref2[0], entityKeyPath = _ref2[1]; if (entityKeyPath === IGNORE_KEY) { return true; } var entityValue = getPropDeep(entity, entityKeyPath); var value = getPropDeep(body, bodyKeyPath); return entityValue === value; }) : true; }; }; var matchEntitiesByQueryFilters = function matchEntitiesByQueryFilters(query, queryMatch) { return function (entity) { return queryMatch ? Object.entries(queryMatch).every(function (_ref3) { var queryKey = _ref3[0], entityKeyPath = _ref3[1]; if (entityKeyPath === IGNORE_KEY) { return true; } var entityValue = getPropDeep(entity, entityKeyPath); return entityValue === query[queryKey]; }) : true; }; }; var getUpdateEntityHandler = function getUpdateEntityHandler(methodConfigs, dataAdapterStorage) { var dataAdapter = dataAdapterStorage.getAdapter(methodConfigs.dataJsonPath); return function (req, res) { try { var responseBuilder = createResponseBuilder(methodConfigs.responseModel); var paramsFilter = matchEntitiesByParams(req.params, methodConfigs.paramMatch); var updatedItem = _extends({}, dataAdapter.updateOne(paramsFilter, req.body, methodConfigs.save), methodConfigs.extensions.withDefaultValues); return Promise.resolve(delay(methodConfigs.delay)).then(function () { if (methodConfigs.returnEntity) { responseBuilder.setData(updatedItem); } responseBuilder.write(res); }); } catch (e) { return Promise.reject(e); } }; }; var baseUrl = ''; var getBaseUrl = function getBaseUrl() { return baseUrl; }; var getAppUrl = function getAppUrl(path) { return lightJoin(getBaseUrl(), path); }; var getReadListEntityHandler = function getReadListEntityHandler(methodConfigs, dataAdapterStorage) { var dataAdapter = dataAdapterStorage.getAdapter(methodConfigs.dataJsonPath); return function (req, res) { try { var responseBuilder = createResponseBuilder(methodConfigs.responseModel); var paramsFilter = matchEntitiesByParams(req.params, methodConfigs.paramMatch); var queryFilter = matchEntitiesByQueryFilters(req.query, methodConfigs.queryMatch); var bodyFilter = matchEntitiesByBodyFilters(req.body, methodConfigs.bodyMatch); var requestedItems = dataAdapter.getAll(function (item) { return paramsFilter(item) && queryFilter(item) && bodyFilter(item); }); var finalItems = requestedItems.map(function (item) { return _extends({}, item, methodConfigs.extensions.withDefaultValues); }); return Promise.resolve(delay(methodConfigs.delay)).then(function () { responseBuilder.setData(finalItems); responseBuilder.write(res); }); } catch (e) { return Promise.reject(e); } }; }; var getReadOneEntityHandler = function getReadOneEntityHandler(methodConfigs, dataAdapterStorage) { var dataAdapter = dataAdapterStorage.getAdapter(methodConfigs.dataJsonPath); return function (req, res) { try { var responseBuilder = createResponseBuilder(methodConfigs.responseModel); var paramsFilter = matchEntitiesByParams(req.params, methodConfigs.paramMatch); var queryFilter = matchEntitiesByQueryFilters(req.query, methodConfigs.queryMatch); var bodyFilter = matchEntitiesByBodyFilters(req.body, methodConfigs.bodyMatch); var requestedItem = dataAdapter.getOne(function (item) { return paramsFilter(item) && queryFilter(item) && bodyFilter(item); }); var finalItem = _extends({}, requestedItem, methodConfigs.extensions.withDefaultValues); return Promise.resolve(delay(methodConfigs.delay)).then(function () { responseBuilder.setData(finalItem); responseBuilder.write(res); }); } catch (e) { return Promise.reject(e); } }; }; var getDeleteEntityHandler = function getDeleteEntityHandler(methodConfigs, dataAdapterStorage) { var dataAdapter = dataAdapterStorage.getAdapter(methodConfigs.dataJsonPath); return function (req, res) { try { var responseBuilder = createResponseBuilder(methodConfigs.responseModel); var deletedItem = dataAdapter.deleteOne(matchEntitiesByParams(req.params, methodConfigs.paramMatch), methodConfigs.save); return Promise.resolve(delay(methodConfigs.delay)).then(function () { if (methodConfigs.returnEntity) { responseBuilder.setData(deletedItem); } responseBuilder.write(res); }); } catch (e) { return Promise.reject(e); } }; }; var isReadOneOperation = function isReadOneOperation(config) { return config.operation === 'read' && config.readOne; }; var isReadListOperation = function isReadListOperation(config) { return config.operation === 'read' && !config.readOne; }; var isCreateOperation = function isCreateOperation(config) { return config.operation === 'create'; }; var isCreateOperationWithFile = function isCreateOperationWithFile(config) { return isCreateOperation(config) && !!config.handleFile; }; var isUpdateOperation = function isUpdateOperation(config) { return config.operation === 'update'; }; var isPatchOperation = function isPatchOperation(config) { return config.operation === 'patch'; }; var isDeleteOperation = function isDeleteOperation(config) { return config.operation === 'delete'; }; var getPatchEntityHandler = function getPatchEntityHandler(methodConfigs, dataAdapterStorage) { var dataAdapter = dataAdapterStorage.getAdapter(methodConfigs.dataJsonPath); return function (req, res) { try { var responseBuilder = createResponseBuilder(methodConfigs.responseModel); var paramsFilter = matchEntitiesByParams(req.params, methodConfigs.paramMatch); var patchedItem = _extends({}, dataAdapter.patchOne(paramsFilter, req.body, methodConfigs.save), methodConfigs.extensions.withDefaultValues); return Promise.resolve(delay(methodConfigs.delay)).then(function () { if (methodConfigs.returnEntity) { responseBuilder.setData(patchedItem); } responseBuilder.write(res); }); } catch (e) { return Promise.reject(e); } }; }; var getCreateEntityWithFileHandler = function getCreateEntityWithFileHandler(methodConfigs, dataAdapterStorage) { var dataAdapter = dataAdapterStorage.getAdapter(methodConfigs.dataJsonPath); var _methodConfigs$uidFie = methodConfigs.uidField, uidType = _methodConfigs$uidFie.type, uidName = _methodConfigs$uidFie.name; return function (req, res) { try { var responseBuilder = createResponseBuilder(methodConfigs.responseModel); var newDataItems = []; req.files.forEach(function (file) { var _extends2, _methodConfigs$handle, _methodConfigs$handle2; var newDataItem = _extends((_extends2 = {}, _extends2[uidName] = uidType === 'number' ? getNumberId(dataAdapter.getAll(), uidName) : lightUid.genUid(), _extends2), req.body, methodConfigs.extensions.withDefaultValues); ((_methodConfigs$handle = methodConfigs.handleFile.exportedFields) === null || _methodConfigs$handle === void 0 ? void 0 : _methodConfigs$handle.fileName) && setPropDeep(newDataItem, methodConfigs.handleFile.exportedFields.fileName, file.originalname); ((_methodConfigs$handle2 = methodConfigs.handleFile.exportedFields) === null || _methodConfigs$handle2 === void 0 ? void 0 : _methodConfigs$handle2.fileSize) && setPropDeep(newDataItem, methodConfigs.handleFile.exportedFields.fileSize, file.size); newDataItems.push(newDataItem); dataAdapter.addOne(newDataItem, methodConfigs.save); }); var returnData = methodConfigs.returnEntity ? newDataItems : newDataItems.map(function (dataItem) { var _ref; return _ref = {}, _ref[uidName] = dataItem[uidName], _ref; }); return Promise.resolve(delay(methodConfigs.delay)).then(function () { responseBuilder.setData(methodConfigs.handleFile.returnAsArray || returnData.length !== 1 ? returnData : returnData[0]); responseBuilder.write(res); }); } catch (e) { return Promise.reject(e); } }; }; var createRouterForApiMethod = function createRouterForApiMethod(url, apiMethodConfig, dataAdapterStorage) { var router = express.Router(); Object.entries(apiMethodConfig).map(function (_ref) { var _isHttpMethod; var method = _ref[0], methodConfig = _ref[1]; if ((_isHttpMethod = !isHttpMethod(method)) != null ? _isHttpMethod : !methodConfig) { throw new Error("Unknown method " + method + " " + url); } if (isCreateOperationWithFile(methodConfig)) { var upload = multer({ dest: methodConfig.handleFile.outputDirectoryPath }); router[method](url, upload.array(methodConfig.handleFile.sourceField), getCreateEntityWithFileHandler(methodConfig, dataAdapterStorage)); } else { router[method](url, getOperationHandler(methodConfig, dataAdapterStorage)); } console.info('[INFO]', "hit " + method.toUpperCase() + " " + getAppUrl(url) + " for " + methodConfig.operation.toUpperCase() + " operation"); }); return router; }; var getOperationHandler = function getOperationHandler(operationConfig, dataAdapterStorage) { if (isCreateOperation(operationConfig)) { return getCreateEntityHandler(operationConfig, dataAdapterStorage); } else if (isReadOneOperation(operationConfig)) { return getReadOneEntityHandler(operationConfig, dataAdapterStorage); } else if (isReadListOperation(operationConfig)) { return getReadListEntityHandler(operationConfig, dataAdapterStorage); } else if (isUpdateOperation(operationConfig)) { return getUpdateEntityHandler(operationConfig, dataAdapterStorage); } else if (isDeleteOperation(operationConfig)) { return getDeleteEntityHandler(operationConfig, dataAdapterStorage); } else if (isPatchOperation(operationConfig)) { return getPatchEntityHandler(operationConfig, dataAdapterStorage); } var shouldNotHappen = operationConfig; throw new Error("The operation \"" + (shouldNotHappen === null || shouldNotHappen === void 0 ? void 0 : shouldNotHappen.operation) + "\" is not handled!"); }; var readConfigs = function readConfigs(options) { var _options$configsPath; if (options !== null && options !== void 0 && options.configs) { return options.configs; } var filePath = path.resolve(process.cwd(), (_options$configsPath = options === null || options === void 0 ? void 0 : options.configsPath) != null ? _options$configsPath : DEFAULT_CONFIG_PATH); try { var configFile = fs.readFileSync(filePath, { encoding: 'utf-8' }); return json5.parse(configFile); } catch (err) { console.error(err); throw new Error("Config file \"" + filePath + "\" isn't available."); } }; var projectDirectory = process.cwd(); var projectPackageJson = path.resolve(projectDirectory, 'package.json'); var resolveProjectPath = function resolveProjectPath(path$1) { return path.resolve(path$1); }; var createDataAdapter = function createDataAdapter(jsonPath) { var finalPath = resolveProjectPath(jsonPath); var jsonStr = fs.readFileSync(finalPath, { encoding: 'utf-8' }); var data = JSON.parse(jsonStr); var saveData = function saveData() { return fs.writeFileSync(finalPath, JSON.stringify(data, null, 2)); }; return { getAll: function getAll(predicate) { return predicate ? data.filter(predicate) : data; }, getOne: function getOne(predicate) { var _data$find; return (_data$find = data.find(predicate)) != null ? _data$find : null; }, addOne: function addOne(item, save) { data.push(item); save && saveData(); }, deleteOne: function deleteOne(predicate, save) { var itemToDelete = this.getOne(predicate); data = data.filter(function (item) { return item !== itemToDelete; }); save && saveData(); return itemToDelete; }, patchOne: function patchOne(predicate, item, save) { var patchedItem; data = data.map(function (current) { var isPredicate = predicate(current); if (isPredicate) { patchedItem = _extends({}, current, item); } return isPredicate ? patchedItem : current; }); save && saveData(); return patchedItem; }, updateOne: function updateOne(predicate, item, save) { data = data.map(function (current) { return predicate(current) ? item : current; }); save && saveData(); return item; } }; }; var createDataAdapterStorage = function createDataAdapterStorage() { var map = new Map(); return { getAdapter: function getAdapter(jsonPath) { if (map.has(jsonPath)) { return map.get(jsonPath); } var adapter = createDataAdapter(jsonPath); map.set(jsonPath, adapter); return adapter; } }; }; var fixConfigs = function fixConfigs(configs) { var fixedConfigs = _extends({}, configs, { defaultConfigs: merge(DEFAULT_CONFIGS, configs.defaultConfigs) }); if (!configs.apis) { return fixedConfigs; } Object.entries(configs.apis).forEach(function (_ref) { var config = _ref[1]; if (!config) { return; } Object.entries(config).forEach(function (_ref2) { var method = _ref2[0], operationConfig = _ref2[1]; if (!isHttpMethod(method) || !operationConfig) { return; } if (!operationConfig.operation) { operationConfig.operation = methodToOperationMap[method]; } if (operationConfig.operation === 'create') { if (operationConfig.handleFile) { fixCreateOperationWithFile(operationConfig, fixedConfigs.defaultConfigs); } fixCreateOperation(operationConfig, fixedConfigs.defaultConfigs); } else if (operationConfig.operation === 'read') { fixReadOperation(operationConfig); } else if (operationConfig.operation === 'update') { fixUpdateOperation(operationConfig, fixedConfigs.defaultConfigs); } else if (operationConfig.operation === 'patch') { fixPatchOperation(operationConfig, fixedConfigs.defaultConfigs); } else if (operationConfig.operation === 'delete') { fixDeleteOperation(operationConfig, fixedConfigs.defaultConfigs); } fixCommonConfigs(operationConfig, fixedConfigs.defaultConfigs); }); }); return fixedConfigs; }; var methodToOperationMap = { get: 'read', post: 'create', put: 'update', "delete": 'delete', patch: 'patch' }; var fixCreateOperation = function fixCreateOperation(config, defaultConfigs) { config.save = config.save || defaultConfigs.save; config.returnEntity = config.returnEntity || defaultConfigs.returnEntity; config.extensions = config.extensions || { withDefaultValues: {} }; }; var fixReadOperation = function fixReadOperation(config, defaultConfigs) { config.readOne = config.readOne || false; config.extensions = config.extensions || { withDefaultValues: {} }; }; var fixUpdateOperation = function fixUpdateOperation(config, defaultConfigs) { config.save = config.save || defaultConfigs.save; config.returnEntity = config.returnEntity || defaultConfigs.returnEntity; config.extensions = config.extensions || { withDefaultValues: {} }; }; var fixPatchOperation = function fixPatchOperation(config, defaultConfigs) { config.save = config.save || defaultConfigs.save; config.returnEntity = config.returnEntity || defaultConfigs.returnEntity; config.extensions = config.extensions || { withDefaultValues: {} }; }; var fixDeleteOperation = function fixDeleteOperation(config, defaultConfigs) { config.save = config.save || defaultConfigs.save; config.returnEntity = config.returnEntity || defaultConfigs.returnEntity; }; var fixCreateOperationWithFile = function fixCreateOperationWithFile(config, defaultConfigs) { config.handleFile = _extends({}, config.handleFile, { outputDirectoryPath: config.handleFile.outputDirectoryPath || defaultConfigs.handleFile.directoryPath }); }; var fixCommonConfigs = function fixCommonConfigs(config, defaultConfigs) { config.delay = config.delay || defaultConfigs.delay; config.responseModel = merge(defaultConfigs.responseModel, config.responseModel || {}); }; var type = "object"; var properties = { apis: { type: "object", properties: { } }, defaultConfigs: { $ref: "default-config.schema.json" } }; var required = [ "apis", "defaultConfigs" ]; var expressOvenConfig_schema = { type: type, properties: properties, required: required }; var ExpressOvenConfigSchema = { __proto__: null, type: type, properties: properties, required: required, 'default': expressOvenConfig_schema }; var type$1 = "object"; var properties$1 = { save: { type: "boolean" }, readOne: { type: "boolean" }, delay: { type: "number" }, responseModel: { type: "object", properties: { } } }; var defaultConfig_schema = { type: type$1, properties: properties$1 }; var DefaultConfigSchema = { __proto__: null, type: type$1, properties: properties$1, 'default': defaultConfig_schema }; var type$2 = "object"; var properties$2 = { operation: { type: "string", "const": "create" }, uidField: { $ref: "uid-field-config.schema.json" }, save: { type: "boolean" }, returnEntity: { type: "boolean" }, dataJsonPath: { type: "string" }, responseModel: { type: "object", properties: { } }, paramMatch: { type: "object", properties: { } }, delay: { type: "number" }, extensions: { type: "object", properties: { withDefaultValues: { type: "object", properties: { } } } } }; var required$1 = [ "operation", "uidField", "save", "dataJsonPath", "returnEntity" ]; var createEntityOperationConfig_schema = { type: type$2, properties: properties$2, required: required$1 }; var CreateOperationSchema = { __proto__: null, type: type$2, properties: properties$2, required: required$1, 'default': createEntityOperationConfig_schema }; var type$3 = "object"; var properties$3 = { operation: { type: "string", "const": "read" }, readOne: { type: "boolean", "const": true }, paramMatch: { type: "object", properties: { } }, filterMatch: { type: "object", properties: { } }, bodyMatch: { type: "object", properties: { } }, queryMatch: { type: "object", properties: { } }, dataJsonPath: { type: "string" }, responseModel: { type: "object", properties: { } }, delay: { type: "number" }, extensions: { type: "object", properties: { withDefaultValues: { type: "object", properties: { } } } } }; var required$2 = [ "operation", "readOne", "dataJsonPath" ]; var readOneEntityOperationConfig_schema = { type: type$3, properties: properties$3, required: required$2 }; var ReadOneOperationSchema = { __proto__: null, type: type$3, properties: properties$3, required: required$2, 'default': readOneEntityOperationConfig_schema }; var type$4 = "object"; var properties$4 = { operation: { type: "string", "const": "read" }, readOne: { type: "boolean", "const": false }, paramMatch: { type: "object", properties: { } }, filterMatch: { type: "object", properties: { } }, bodyMatch: { type: "object", properties: { } }, queryMatch: { type: "object", properties: { } }, dataJsonPath: { type: "string" }, responseModel: { type: "object", properties: { } }, delay: { type: "number" }, extensions: { type: "object", properties: { withDefaultValues: { type: "object", properties: { } } } } }; var required$3 = [ "operation", "readOne", "dataJsonPath" ]; var readEntityListOperationConfig_schema = { type: type$4, properties: properties$4, required: required$3 }; var ReadListOperationSchema = { __proto__: null, type: type$4, properties: properties$4, required: required$3, 'default': readEntityListOperationConfig_schema }; var type$5 = "object"; var properties$5 = { operation: { type: "string", "const": "update" }, paramMatch: { type: "object", properties: { } }, save: { type: "boolean" }, returnEntity: { type: "boolean" }, dataJsonPath: { type: "string" }, responseModel: { type: "object", properties: { } }, delay: { type: "number" }, extensions: { type: "object", properties: { withDefaultValues: { type: "object", properties: { } } } } }; var required$4 = [ "operation", "paramMatch", "save", "dataJsonPath", "returnEntity" ]; var updateEntityOperationConfig_schema = { type: type$5, properties: properties$5, required: required$4 }; var UpdateOperationSchema = { __proto__: null, type: type$5, properties: properties$5, required: required$4, 'default': updateEntityOperationConfig_schema }; var type$6 = "object"; var properties$6 = { operation: { type: "string", "const": "patch" }, paramMatch: { type: "object", properties: { } }, save: { type: "boolean" }, returnEntity: { type: "boolean" }, dataJsonPath: { type: "string" }, responseModel: { type: "object", properties: { } }, delay: { type: "number" }, extensions: { type: "object", properties: { withDefaultValues: { type: "object", properties: { } } } } }; var required$5 = [ "operation", "paramMatch", "save", "dataJsonPath", "returnEntity" ]; var patchEntityOperationConfig_schema = { type: type$6, properties: properties$6, required: required$5 }; var PatchOperationSchema = { __proto__: null, type: type$6, properties: properties$6, required: required$5, 'default': patchEntityOperationConfig_schema }; var type$7 = "object"; var properties$7 = { operation: { type: "string", "const": "delete" }, save: { type: "boolean" }, paramMatch: { type: "object", properties: { } }, dataJsonPath: { type: "string" }, responseModel: { type: "object", properties: { } }, delay: { type: "number" } }; var required$6 = [ "operation", "paramMatch", "save", "dataJsonPath" ]; var deleteEntityOperationConfig_schema = { type: type$7, properties: properties$7, required: required$6 }; var DeleteOperationSchema = { __proto__: null, type: type$7, properties: properties$7, required: required$6, 'default': deleteEntityOperationConfig_schema }; var type$8 = "object"; var required$7 = [ "name", "type" ]; var properties$8 = { name: { type: "string" }, type: { type: "string" } }; var uidFieldConfig_schema = { type: type$8, required: required$7, properties: properties$8 }; var UidFieldSchema = { __proto__: null, type: type$8, required: required$7, properties: properties$8, 'default': uidFieldConfig_schema }; var ajv = new Ajv({ allErrors: true }); ajv.addSchema(ExpressOvenConfigSchema, 'express-oven-config.schema.json'); ajv.addSchema(DefaultConfigSchema, 'default-config.schema.json'); ajv.addSchema(CreateOperationSchema, 'create-entity-operation-config.schema.json'); ajv.addSchema(ReadOneOperationSchema, 'read-one-entity-operation-config.schema.json'); ajv.addSchema(ReadListOperationSchema, 'read-entity-list-operation-config.schema.json'); ajv.addSchema(UpdateOperationSchema, 'update-entity-operation-config.schema.json'); ajv.addSchema(PatchOperationSchema, 'patch-entity-operation-config.schema.json'); ajv.addSchema(DeleteOperationSchema, 'delete-entity-operation-config.schema.json'); ajv.addSchema(UidFieldSchema, 'uid-field-config.schema.json'); var validateConfigs = function validateConfigs(configs) { ajv.validate('express-oven-config.schema.json', configs); Object.entries(configs.apis).forEach(function (_ref) { var config = _ref[1]; Object.entries(config).forEach(function (_ref2) { var method = _ref2[0], operationConfig = _ref2[1]; if (!isHttpMethod(method) || !operationConfig) { throw new Error("Unknown method '" + method + "'"); } if (isCreateOperation(operationConfig)) { ajv.validate('create-entity-operation-config.schema.json', operationConfig); } else if (isReadOneOperation(operationConfig)) { ajv.validate('read-one-entity-operation-config.schema.json', operationConfig); } else if (isReadListOperation(operationConfig)) { ajv.validate('read-entity-list-operation-config.schema.json', operationConfig); } else if (isUpdateOperation(operationConfig)) { ajv.validate('update-entity-operation-config.schema.json', operationConfig); } else if (isPatchOperation(operationConfig)) { ajv.validate('patch-entity-operation-config.schema.json', operationConfig); } else if (isDeleteOperation(operationConfig)) { ajv.validate('delete-entity-operation-config.schema.json', operationConfig); } }); }); console.log(ajv.errors); return !!ajv.errors; }; var defaultValue = null; var tryParse = function tryParse(str) { if (str === void 0) { str = defaultValue; } if (typeof str !== 'string') { return str; } try { return JSON.parse(str); } catch (err) { return str; } }; var universalBodyParser = function universalBodyParser(req, res, next) { req.body = tryParse(req.body); next(); }; var createExpressOvenRoutes = function createExpressOvenRoutes(options) { var router = express.Router(); router.use(universalBodyParser); var dataAdapterStorage = createDataAdapterStorage(); var configs = fixConfigs(readConfigs(options)); validateConfigs(configs); Object.entries(configs.apis).map(function (_ref) { var url = _ref[0], methodConfigs = _ref[1]; router.use(createRouterForApiMethod(url, methodConfigs, dataAdapterStorage)); }); return router; }; exports.createExpressOvenRoutes = createExpressOvenRoutes; //# sourceMappingURL=index.js.map