Best JavaScript code snippet using apimocker
apimocker.js
Source:apimocker.js
1var express = require('express'),2 _ = require('underscore'),3 path = require('path'),4 fs = require('fs'),5 bodyParser = require('body-parser'),6 xmlparser = require('express-xml-bodyparser'),7 apiMocker = {},8 jsonPath = require('JSONPath'),9 untildify = require('untildify'),10 util = require('util'),11 proxy = require('express-http-proxy');12apiMocker.defaults = {13 'port': '8888',14 'mockDirectory': './mocks/',15 'allowedDomains': ['*'],16 'allowedHeaders': ['Content-Type'],17 'logRequestHeaders': false,18 'webServices': {}19};20apiMocker.createServer = function(options) {21 options = options || {};22 function logger(msg, obj) {23 if (!options.quiet) {24 if (obj) {25 // console.log(msg, obj);26 } else {27 // console.log(msg);28 }29 }30 }31 apiMocker.express = express();32 apiMocker.middlewares = [];33 var saveBody;34 if (options.proxyURL) {35 saveBody = function(req, res, buf) {36 req.rawBody = buf;37 };38 }39 apiMocker.middlewares.push(bodyParser.urlencoded({40 extended: true,41 verify: saveBody42 }));43 apiMocker.middlewares.push(bodyParser.json({44 verify: saveBody45 }));46 apiMocker.middlewares.push(xmlparser());47 apiMocker.middlewares.push(apiMocker.corsMiddleware);48 // new in Express 4, we use a Router now.49 apiMocker.router = express.Router();50 apiMocker.middlewares.push(apiMocker.router);51 if (options.proxyURL) {52 logger("Proxying to " + options.proxyURL);53 var proxyOptions = {54 forwardPath: function(req) {55 logger("Forwarding request: " + req.originalUrl);56 return req.originalUrl;57 }58 };59 if (options.proxyIntercept) {60 var interceptPath = path.join(process.cwd(), options.proxyIntercept);61 logger("Loading proxy intercept from " + interceptPath);62 proxyOptions.intercept = require(interceptPath);63 }64 apiMocker.middlewares.push(function(req, res, next) {65 if (req.rawBody) {66 req.body = req.rawBody;67 }68 next();69 });70 apiMocker.middlewares.push(proxy(options.proxyURL, proxyOptions));71 }72 apiMocker.options = _.defaults(options, apiMocker.defaults);73 apiMocker.log = logger;74 return apiMocker;75};76apiMocker.setConfigFile = function(file) {77 if (!file) {78 return apiMocker;79 } else if (path.sep !== file.substr(0, 1)) {80 //relative path from command line81 apiMocker.configFilePath = path.resolve(process.cwd(), file);82 } else {83 apiMocker.configFilePath = file;84 }85 return apiMocker;86};87apiMocker.loadConfigFile = function() {88 if (apiMocker.configFilePath) {89 apiMocker.log('Loading config file: ' + apiMocker.configFilePath);90 // Switched to use fs.readFileSync instead of 'require'91 // this makes testing easier, and avoids messing with require cache.92 var newOptions = _.clone(apiMocker.defaults),93 configJson = JSON.parse(fs.readFileSync(apiMocker.configFilePath));94 if (process.env.VCAP_APP_PORT) {95 // we're running in cloudfoundry, and we need to use the VCAP port.96 configJson.port = process.env.VCAP_APP_PORT;97 }98 newOptions = _.extend(newOptions, apiMocker.options, configJson);99 newOptions.mockDirectory = untildify(newOptions.mockDirectory);100 apiMocker.options = newOptions;101 _.each(apiMocker.options.webServices, function(svc) {102 _.each(svc.alternatePaths, function(path) {103 var altSvc = _.clone(svc);104 apiMocker.options.webServices[path] = altSvc;105 });106 });107 apiMocker.setRoutes(apiMocker.options.webServices);108 } else {109 apiMocker.log('No config file path set.');110 }111};112apiMocker.createAdminServices = function() {113 apiMocker.router.all('/admin/reload', function(req, res) {114 apiMocker.stop();115 apiMocker.createServer(apiMocker.options).start();116 res.writeHead(200, { 'Content-Type': 'application/json' });117 res.end('{"configFilePath": "' + apiMocker.configFilePath + '", "reloaded": "true"}');118 });119 apiMocker.router.all('/admin/setMock', function(req, res) {120 var newRoute = {};121 if (req.body.serviceUrl && req.body.verb && req.body.mockFile) {122 apiMocker.log('Received JSON request: ' + JSON.stringify(req.body));123 newRoute = req.body;124 newRoute.verb = newRoute.verb.toLowerCase();125 newRoute.httpStatus = req.body.httpStatus;126 } else {127 newRoute.verb = req.param('verb').toLowerCase();128 newRoute.serviceUrl = req.param('serviceUrl');129 newRoute.mockFile = req.param('mockFile');130 newRoute.latency = req.param('latency');131 newRoute.contentType = req.param('contentType');132 newRoute.httpStatus = req.param('httpStatus');133 }134 // also need to save in our webServices object.135 delete apiMocker.options.webServices[newRoute.serviceUrl];136 apiMocker.options.webServices[newRoute.serviceUrl] = newRoute;137 apiMocker.setRoute(newRoute);138 res.writeHead(200, { 'Content-Type': 'application/json' });139 res.end(JSON.stringify(newRoute));140 });141};142apiMocker.setRoutes = function(webServices) {143 var topLevelKeys = _.keys(webServices);144 _.each(topLevelKeys, function(key) {145 var svc = _.clone(webServices[key]);146 // apiMocker.log('about to add a new service: ' + JSON.stringify(svc));147 _.each(svc.verbs, function(v) {148 apiMocker.setRoute(apiMocker.getServiceRoute(key, v));149 });150 });151};152apiMocker.getServiceRoute = function(path, verb) {153 var finalSvc = _.clone(apiMocker.options.webServices[path]);154 finalSvc.verb = verb.toLowerCase();155 finalSvc.serviceUrl = path;156 if (finalSvc.responses) {157 finalSvc = _.extend(finalSvc, finalSvc.responses[verb]);158 }159 if (typeof finalSvc.latency === 'undefined') {160 finalSvc.latency = apiMocker.options.latency ? apiMocker.options.latency : 0;161 }162 delete finalSvc.responses;163 delete finalSvc.verbs;164 return finalSvc;165};166// Fills in templated Values.167apiMocker.fillTemplate = function(data, req) {168 for (var templateString in req.params) {169 data = data.replace(new RegExp('@' + templateString, 'g'), req.param(templateString));170 }171 return data;172};173apiMocker.fillTemplateSwitch = function(options, data) {174 var switches = options.templateSwitch;175 switches.forEach(function(s) {176 var key, value;177 if (!(s instanceof Object)) {178 key = switches[s].key;179 value = switches[s].value;180 } else {181 key = s.key;182 value = s.value;183 }184 if (typeof value !== null) {185 apiMocker.log('fillTemplateSwitch -> search for @' + key + ' replace with ' + value);186 data = data.replace(new RegExp('@' + key, 'g'), value);187 } else {188 apiMocker.log('fillTemplateSwitch -> skipping search for @' + key + ' with no value.');189 }190 });191 return data;192};193apiMocker.sendResponse = function(req, res, serviceKeys) {194 // console.log(req);195 var originalOptions, mockPath;196 // we want to look up the service info from our in-memory 'webServices' every time.197 var options = apiMocker.getServiceRoute(serviceKeys.serviceUrl, serviceKeys.verb);198 setTimeout(function() {199 if (options.httpStatus === 204 || options.httpStatus === 304) {200 // express handles these two differently - it strips out body, content-type, and content-length headers.201 // there's no body or content-length, so we just send the status code.202 apiMocker.log('Returning http status: ' + options.httpStatus);203 res.send(options.httpStatus);204 return;205 }206 if (options.switch) {207 options = _.clone(options);208 originalOptions = _.clone(options);209 apiMocker.setSwitchOptions(options, req);210 mockPath = path.join(apiMocker.options.mockDirectory, options.mockFile || '');211 if (!fs.existsSync(mockPath)) {212 apiMocker.log('No file found: ' + options.mockFile + ' attempting base file: ' + originalOptions.mockFile);213 options.mockFile = originalOptions.mockFile;214 }215 }216 if (options.templateSwitch) {217 apiMocker.setTemplateSwitchOptions(options, req);218 }219 if (apiMocker.options.logRequestHeaders) {220 apiMocker.log('Request headers:');221 apiMocker.log(req.headers);222 }223 if (options.headers) {224 res.header(options.headers);225 }226 if (!options.mockFile) {227 var status = options.httpStatus || 404;228 apiMocker.log('No mockFile found. Returning httpStatus: ', status);229 res.status(status).send();230 return;231 }232 mockPath = path.join(apiMocker.options.mockDirectory, options.mockFile);233 apiMocker.log('Returning mock: ' + options.verb.toUpperCase() + ' ' + options.serviceUrl + ' : ' +234 options.mockFile);235 fs.exists(mockPath, function(exists) {236 if (exists) {237 if (options.contentType) {238 res.header('Content-Type', options.contentType);239 fs.readFile(mockPath, { encoding: 'utf8' }, function(err, data) {240 if (err) { throw err; }241 if (options.templateSwitch) {242 data = apiMocker.fillTemplateSwitch(options, data, req);243 }244 if (options.enableTemplate === true) {245 data = apiMocker.fillTemplate(data, req);246 }247 var buff = new Buffer(data, 'utf8');248 res.status(options.httpStatus || 200).send(buff);249 });250 } else {251 res.status(options.httpStatus || 200).sendfile(encodeURIComponent(options.mockFile), { root: apiMocker.options.mockDirectory });252 }253 } else {254 res.send(options.httpStatus || 404);255 }256 });257 }, options.latency);258};259// only used when there is a switch configured260apiMocker.setSwitchOptions = function(options, req) {261 var switchFilePrefix = '',262 switchParamValue,263 mockFileParts, mockFilePrefix = '',264 mockFileBaseName;265 var switches = options.switch;266 if (!(switches instanceof Array)) {267 switches = [switches];268 }269 switches.forEach(function(s) {270 switchParamValue = null;271 var switchObject = s,272 specific = true;273 if (!(s instanceof Object)) {274 // The user didn't configure a switch object. Make one.275 switchObject = {276 key: s,277 switch: s,278 type: 'default'279 };280 if (s.match(/\/(.+)\//)) {281 switchObject.type = 'regexp';282 } else if (s.indexOf('$') === 0) {283 switchObject.type = 'jsonpath';284 }285 // As we had no switch object, we have to test default-type first to286 // mimic the old behaviour.287 specific = false;288 }289 if (!switchObject.hasOwnProperty('key')) {290 // Add key if the user was too lazy291 switchObject.key = switchObject.switch;292 }293 // Sanity check the switchobject294 if (!switchObject.hasOwnProperty('switch') ||295 !switchObject.hasOwnProperty('type') ||296 !switchObject.hasOwnProperty('key')297 ) {298 return;299 }300 if (!specific || switchObject.type === 'default') {301 if (req.body[switchObject.switch]) { // json post request302 switchParamValue = encodeURIComponent(req.body[switchObject.switch]);303 } else if (req.param(switchObject.switch)) { // query param in get request304 switchParamValue = encodeURIComponent(req.param(switchObject.switch));305 } else if (req.headers) { // check for switch in header param306 for (var h in req.headers) {307 if (req.headers.hasOwnProperty(h) && h.toLowerCase() === switchObject.switch.toLowerCase()) {308 switchParamValue = encodeURIComponent(req.headers[h]);309 break;310 }311 }312 }313 }314 if (!switchParamValue) {315 if (switchObject.type === 'regexp') {316 var regexpTest = switchObject.switch.match(/\/(.+)\//);317 if (regexpTest) { // A regexp switch318 var searchBody = req.body;319 if (typeof(req.body) !== 'string') {320 // We don't have a body string, parse it in JSON321 searchBody = JSON.stringify(req.body);322 }323 var regexpSwitch = new RegExp(regexpTest[1]).exec(searchBody);324 if (regexpSwitch) {325 // Value is the first group326 switchParamValue = encodeURIComponent(regexpSwitch[1]);327 }328 }329 } else {330 //use JsonPath - use first value found if multiple occurances exist331 var allElems = jsonPath.eval(req.body, switchObject.switch); // jshint ignore:line332 if (allElems.length > 0) {333 switchParamValue = encodeURIComponent(allElems[0]);334 }335 }336 }337 if (switchParamValue) {338 // console.log(switchParamValue);339 switchFilePrefix = switchFilePrefix + switchObject.key + switchParamValue;340 // console.log(switchFilePrefix);341 }342 });343 if (!switchFilePrefix) {344 return;345 }346 if (options.switchResponses && options.switchResponses[switchFilePrefix]) {347 _.extend(options, options.switchResponses[switchFilePrefix]);348 if (options.switchResponses[switchFilePrefix].mockFile) {349 return;350 }351 }352 if (options.mockFile) {353 mockFileParts = options.mockFile.split('/');354 mockFileBaseName = mockFileParts.pop();355 if (mockFileParts.length > 0) {356 mockFilePrefix = mockFileParts.join('/') + '/';357 }358 options.mockFile = mockFilePrefix + switchFilePrefix + '.' + mockFileBaseName;359 }360};361// only used when there is a templateSwitch configured362apiMocker.setTemplateSwitchOptions = function(options, req) {363 var switchParamValue;364 var switches = options.templateSwitch;365 if (!(switches instanceof Array)) {366 switches = [switches];367 }368 switches.forEach(function(s) {369 switchParamValue = null;370 var switchObject = s,371 specific = true;372 if (!(s instanceof Object)) {373 // The user didn't configure a switch object. Make one.374 switchObject = {375 key: s,376 switch: s,377 type: 'default',378 value: null379 };380 if (s.match(/\/(.+)\//)) {381 switchObject.type = 'regexp';382 } else if (s.indexOf('$') === 0) {383 switchObject.type = 'jsonpath';384 }385 // As we had no switch object, we have to test default-type first to386 // mimic the old behaviour.387 specific = false;388 }389 if (!switchObject.hasOwnProperty('key')) {390 // Add key if the user was too lazy391 switchObject.key = switchObject.switch;392 }393 // Sanity check the switchobject394 if (!switchObject.hasOwnProperty('switch') ||395 !switchObject.hasOwnProperty('type') ||396 !switchObject.hasOwnProperty('key')397 ) {398 apiMocker.log('templateSwitch invalid config: missing switch, type or key property. Aborting templateSwitch for this request.');399 return;400 }401 if (!specific || switchObject.type === 'default') {402 if (req.body[switchObject.switch]) { // json post request403 switchParamValue = encodeURIComponent(req.body[switchObject.switch]);404 } else if (req.param(switchObject.switch)) { // query param in get request405 switchParamValue = encodeURIComponent(req.param(switchObject.switch));406 } else if (req.headers) { // check for switch in header param407 for (var h in req.headers) {408 if (req.headers.hasOwnProperty(h) && h.toLowerCase() === switchObject.switch.toLowerCase()) {409 switchParamValue = encodeURIComponent(req.headers[h]);410 break;411 }412 }413 }414 }415 if (!switchParamValue) {416 if (switchObject.type === 'regexp') {417 var regexpTest = switchObject.switch.match(/\/(.+)\//);418 if (regexpTest) { // A regexp switch419 var searchBody = req.body;420 if (typeof(req.body) !== 'string') {421 // We don't have a body string, parse it in JSON422 searchBody = JSON.stringify(req.body);423 }424 var regexpSwitch = new RegExp(regexpTest[1]).exec(searchBody);425 if (regexpSwitch) {426 // Value is the first group427 switchParamValue = encodeURIComponent(regexpSwitch[1]);428 }429 }430 } else {431 //use JsonPath - use first value found if multiple occurances exist432 var allElems = jsonPath.eval(req.body, switchObject.switch); // jshint ignore:line433 if (allElems.length > 0) {434 switchParamValue = encodeURIComponent(allElems[0]);435 }436 }437 }438 if (switchParamValue) {439 switchObject.value = switchParamValue;440 options.templateSwitch[s] = switchObject;441 } else {442 apiMocker.log('templateSwitch[' + switchObject.switch+'] value NOT FOUND');443 }444 });445};446// Sets the route for express, in case it was not set yet.447apiMocker.setRoute = function(options) {448 var displayFile = options.mockFile || '<no mockFile>',449 displayLatency = options.latency ? options.latency + ' ms' : '';450 apiMocker.router[options.verb]('/' + options.serviceUrl, function(req, res) {451 apiMocker.sendResponse(req, res, options);452 });453 apiMocker.log('Set route: ' + options.verb.toUpperCase() + ' ' + options.serviceUrl + ' : ' +454 displayFile + ' ' + displayLatency);455 if (options.switch) {456 var switchDescription = options.switch;457 if (options.switch instanceof Array || Â options.switch instanceof Object) {458 switchDescription = util.inspect(options.switch);459 }460 apiMocker.log(' with switch on param: ' + switchDescription);461 }462};463// CORS middleware464apiMocker.corsMiddleware = function(req, res, next) {465 var allowedHeaders = apiMocker.options.allowedHeaders.join(',');466 var credentials = apiMocker.options.corsCredentials || '';467 res.header('Access-Control-Allow-Origin', apiMocker.options.allowedDomains);468 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,PATCH,DELETE');469 res.header('Access-Control-Allow-Headers', allowedHeaders);470 res.header('Access-Control-Allow-Credentials', credentials);471 next();472};473apiMocker.start = function(port, callback) {474 apiMocker.createAdminServices();475 apiMocker.loadConfigFile();476 apiMocker.middlewares.forEach(function(mw) {477 if (mw === apiMocker.router && apiMocker.options.basepath) {478 apiMocker.log('Using basepath: ', apiMocker.options.basepath);479 apiMocker.express.use(apiMocker.options.basepath, mw);480 } else {481 apiMocker.express.use(mw);482 }483 });484 port = port || apiMocker.options.port;485 // console.log(JSON.stringify(apiMocker.options));486 if (apiMocker.options.staticDirectory && apiMocker.options.staticPath) {487 apiMocker.express.use(apiMocker.options.staticPath, express.static(apiMocker.options.staticDirectory));488 }489 apiMocker.expressInstance = apiMocker.express.listen(port, callback);490 apiMocker.log('Mock server listening on port ' + port);491 return apiMocker;492};493apiMocker.stop = function(callback) {494 if (apiMocker.expressInstance) {495 apiMocker.log('Stopping mock server.');496 apiMocker.expressInstance.close(callback);497 }498 return apiMocker;499};500// expose all the 'public' methods.501exports.createServer = apiMocker.createServer;502exports.start = apiMocker.start;503exports.setConfigFile = apiMocker.setConfigFile;504exports.stop = apiMocker.stop;...
Using AI Code Generation
1var apimocker = require('apimocker');2var fs = require('fs');3var path = require('path');4var express = require('express');5var app = express();6var server = require('http').createServer(app);7var io = require('socket.io')(server);8var config = JSON.parse(fs.readFileSync('config.json'));9server.listen(config.port, function () {10 console.log('Server listening at port %d', config.port);11});12apimocker({13});14app.get('/', function (req, res) {15 res.sendfile(path.join(__dirname, 'index.html'));16});17app.get('/test', function (req, res) {18 res.sendfile(path.join(__dirname, 'index.html'));19});20app.get('/test2', function (req, res) {21 res.sendfile(path.join(__dirname, 'index.html'));22});23app.get('/test3', function (req, res) {24 res.sendfile(path.join(__dirname, 'index.html'));25});26app.get('/test4', function (req, res) {27 res.sendfile(path.join(__dirname, 'index.html'));28});29app.get('/test5', function (req, res) {30 res.sendfile(path.join(__dirname, 'index.html'));31});32app.get('/test6', function (req, res) {33 res.sendfile(path.join(__dirname, 'index.html'));34});35app.get('/test7', function (req, res) {36 res.sendfile(path.join(__dirname, 'index.html'));37});38app.get('/test8', function (req, res) {39 res.sendfile(path.join(__dirname, 'index.html'));40});41app.get('/test9', function (req, res) {42 res.sendfile(path.join(__dirname, 'index.html'));43});44app.get('/test10', function (req, res)
Using AI Code Generation
1var apimocker = require('apimocker');2var apiMocker = new apimocker();3var regexpSwitch = new apiMocker.regexpSwitch();4regexpSwitch.addRegexpRule(".*", "test.js");5apiMocker.setDefaultHandler(regexpSwitch);6apiMocker.startServer();7var apimocker = require('apimocker');8var apiMocker = new apimocker();9var regexpSwitch = new apiMocker.regexpSwitch();10regexpSwitch.addRegexpRule(".*", "test.js");11apiMocker.setDefaultHandler(regexpSwitch);12apiMocker.startServer();13var regexpSwitch = new apiMocker.regexpSwitch();14regexpSwitch.addRegexpRule(".*", "test.js");15var regexpSwitch = new apiMocker.regexpSwitch();16regexpSwitch.addRegexpRule(".*", "test.js");17var regexpSwitch = new apiMocker.regexpSwitch();18regexpSwitch.addRegexpRule(".*", "test.js");19var regexpSwitch = new apiMocker.regexpSwitch();
Using AI Code Generation
1var apimocker = require('apimocker');2var express = require('express');3var app = express();4var mocker = apimocker({5});6mocker.start();7app.use(mocker.middleware);8app.listen(8080);9{10 "api": {11 "response": {12 "body": {13 }14 }15 }16}17{18 "api": {19 "response": {20 "body": {21 }22 }23 }24}25{26 "api": {27 "response": {28 "body": {29 }30 }31 }32}33{34 "api": {35 "response": {36 "body": {37 }38 }39 }40}41{42 "api": {43 "response": {44 "body": {45 }46 }47 }48}49{50 "api": {51 "response": {52 "body": {
Using AI Code Generation
1var regexpSwitch = require('apimocker').regexpSwitch;2module.exports = function(app) {3 app.get('/api/v1/employees/:id', regexpSwitch([4 {5 response: {6 data: {
Using AI Code Generation
1var apimocker = require('apimocker');2apimocker.regexpSwitch({3});4var apimocker = require('apimocker');5apimocker.regexpSwitch({6});7var apimocker = require('apimocker');8apimocker.regexpSwitch({9});10var apimocker = require('apimocker');11apimocker.regexpSwitch({
Using AI Code Generation
1var apimocker = require('apimocker');2apimocker.regexpSwitch({3});4{5 "request": {6 },7 "response": {8 "data": {9 },10 "headers": {11 }12 }13}14{15 "request": {16 },17 "response": {18 "data": {19 },20 "headers": {21 }22 }23}24{25 "request": {26 },27 "response": {28 "data": {29 },30 "headers": {31 }32 }33}34{35 "request": {36 },37 "response": {38 "data": {39 },40 "headers": {41 }42 }43}44{45 "request": {46 },47 "response": {48 "data": {49 },50 "headers": {51 }
Using AI Code Generation
1var regexpSwitch = require('./lib/regexpSwitch');2regexpSwitch({3 headers: {4 },5 body: {6 }7}, function(err, res, body) {8 console.log(body);9});10var regexpSwitch = require('./lib/regexpSwitch');11regexpSwitch({12 headers: {13 },14 body: {15 }16}, function(err, res, body) {17 console.log(body);18});19var regexpSwitch = require('./lib/regexpSwitch');20regexpSwitch({21 headers: {22 },23 body: {24 }25}, function(err, res, body) {26 console.log(body);27});28var regexpSwitch = require('./lib/regexpSwitch');29regexpSwitch({
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!