This repository has been archived by the owner on Nov 21, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
controller.js
96 lines (80 loc) · 2.88 KB
/
controller.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* Copyright (c) 2014, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
/*jshint node:true */
'use strict';
var fs = require('fs');
var path = require('path');
var argv = require('yargs').argv;
var FakeResponse = require('./fakeresponse.js');
var merge = require('merge');
// Preload routes
FakeResponse.preload(argv.configDir);
var controller = {
fakeResponse: FakeResponse, // of course this is here just so that it can be overwritten easily in the tests.
add: function (req, res, next) {
var obj = {
delay: req.params.delay,
at: req.params.at,
route: req.params.route,
queryParams: req.params.queryParams,
payload: req.params.payload,
responseCode: req.params.responseCode,
responseBody: decodeURIComponent(req.params.responseBody.replace(/"/g, '"')),
};
controller.fakeResponse.add(obj);
res.send(200, 'OK');
next();
},
match: function (req, res, next) {
function send (statusCode, responseHeaders, responseBody) {
if (typeof responseBody === "object") {
try {
responseBody = JSON.stringify(responseBody);
} catch (e) {
responseBody = "Unable to serialize responseBody";
res.statusCode = 500;
}
}
responseHeaders['Content-Length'] = Buffer.byteLength(responseBody);
res.writeHead(statusCode, responseHeaders);
res.write(responseBody);
res.end();
}
var bestMatch = controller.fakeResponse.match(req.url, req.body, req.headers);
if (bestMatch) {
var headers = {
'Content-Type': 'application/json'
};
if(bestMatch.responseHeaders) {
headers = merge(headers, bestMatch.responseHeaders);
}
if(bestMatch.responseData) {
fs.readFile(path.join(__dirname, bestMatch.responseData),'utf8', function(err, data) {
if (err) {
res.send(500, "FAKE-SERVER is misconfigured");
}
send(parseInt(bestMatch.responseCode, 10), headers, data);
});
} else {
send(parseInt(bestMatch.responseCode, 10), headers, bestMatch.responseBody);
}
if (bestMatch.delay) {
setTimeout(next, bestMatch.delay);
} else {
next();
}
} else {
res.send(404, 'no match!');
next();
}
},
flush: function (req, res, next) {
controller.fakeResponse.flush();
res.send(200, 'OK');
next();
}
};
module.exports = controller;