UNPKG

x-mock

Version:

Mock response generator for OAS.

117 lines (101 loc) 3.33 kB
const Parser = require('swagger-parser'); const Generators = require('./generators'); const ParamTypes = require('./generators/paramtypes'); const Querystring = require('querystring'); const Maybe = require('call-me-maybe'); const OPERATIONS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch']; module.exports = (api, options) => { return new Xmock(api, options); }; function XmockException(message) { this.message = message; this.name = 'XmockException'; } function Xmock(api, { validated, mixins } = {}) { //If the api is an already validated Object, use it as it is. //If not validated, Parse and validate using 'swagger-parser' this.swagger = validated ? Promise.resolve(api) : Parser.validate(api); Generator = Generators(mixins); } Xmock.prototype.response = function (options = {}, callback) { options.mockResponses = true; return Maybe(callback, this.mock(options)); }; Xmock.prototype.mock = function (options = {}) { return this.swagger.then(api => { return mockSchema(api, options); }); }; const mockSchema = (api, options) => { let mock = {}; let paths = api.paths; if (paths) { let pathObj = paths[options.path]; if (pathObj) { //Found the requested path return mockPath(options.path, pathObj, mock, options); } else { // path not found. throw new XmockException(`The path ${options.path} not found in OAS.`); } } //return mock; }; /** * Generate mock for the path */ const mockPath = (pathStr, pathObj, mock, options) => { let operationObj = pathObj[options.operation]; //Common parameters - A list of parameters that are applicable for //all the operations described under this path let commParams = pathObj.parameters; if (operationObj) { //Found the operation return mockOperation({ path: pathStr, operation: options.operation, commonParams: commParams }, operationObj, mock, options); } else { // operation not found. throw new XmockException(`The operation ${options.operation} not found in OAS.`); } }; /** * Generate mock for the operation */ const mockOperation = (resolved, operationObj, mock, options) => { //Mock response if (options.mockResponses) { return mockResponses(operationObj, options); } }; /** * Generate a mock responses * */ const mockResponses = (operationObj, options) => { let mockResp; let responses = operationObj.responses; //get responses from oas if (responses) { let code; for (let key in responses) { if (responses[key]['x-mock']) { code = Number(key) } } if (!code) code = 200; let response = responses[code]; //match to passed in response code e.g. 200 let mock = { code, type: 'application/json' }; //TODO if (response && response.schema) { //Found the response mock.body = Generator.mock(response.schema); return mock; } else if (response) { return mock; } else { //Response not found. throw new XmockException(`The response ${code} not found in OAS.`); } } };