From ac6c61300d5ebd3a438d4eafec4383b436688f3c Mon Sep 17 00:00:00 2001 From: Aaryaman Vasishta Date: Thu, 16 Mar 2017 12:28:28 +0900 Subject: [PATCH] Add a complimentary route to /bin for delayed response. --- lib/routes/bins.js | 1 + lib/routes/bins/delayed_run.js | 57 ++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 lib/routes/bins/delayed_run.js diff --git a/lib/routes/bins.js b/lib/routes/bins.js index f54fbc1a..f7d4aa61 100644 --- a/lib/routes/bins.js +++ b/lib/routes/bins.js @@ -30,6 +30,7 @@ module.exports = function bins (dsn_str) { { action: 'get', path: '/:uuid/view', route: routes.view.bind(this) }, { action: 'get', path: '/:uuid/sample', route: routes.sample.bind(this) }, { action: 'get', path: '/:uuid/log', route: routes.log.bind(this) }, + { action: 'all', path: '/:uuid/delay/:ms?', route: routes.delayed_run.bind(this) }, { action: 'all', path: '/:uuid*', route: routes.run.bind(this) } ] diff --git a/lib/routes/bins/delayed_run.js b/lib/routes/bins/delayed_run.js new file mode 100644 index 00000000..ced9a626 --- /dev/null +++ b/lib/routes/bins/delayed_run.js @@ -0,0 +1,57 @@ +'use strict' + +var debug = require('debug-log')('mockbin') + +module.exports = function (req, res, next) { + this.client.get('bin:' + req.params.uuid, function (err, value) { + if (err) { + debug(err) + + throw err + } + // delayed bin response + var delay = req.params.ms ? parseInt(req.params.ms, 10) : 200 + + if (delay > 60000) { + delay = 60000 + } + + if (value) { + var har = JSON.parse(value) + + // log interaction & send the appropriate response based on HAR + this.client.rpush('log:' + req.params.uuid, JSON.stringify(req.har.log.entries[0])) + this.client.ltrim('log:' + req.params.uuid, 0, 100) + + setTimeout(function () { + + // headers + har.headers.map(function (header) { + res.set(header.name, header.value) + }) + + // delay header + res.set("mockbin-delay", delay) + + // cookies + har.cookies.map(function (cookie) { + res.cookie(cookie.name, cookie.value) + }) + + // status + res.httpVersion = har.httpVersion.split('/')[1] + res.statusCode = har.status || 200 + res.statusMessage = har.statusText || 'OK' + + // special condition + if (har.redirectURL !== '') { + res.location(har.redirectURL) + } + + res.body = har.content.text ? har.content.text : null + + next() + }, delay) + } + }.bind(this)) +}