/
test-server.js
189 lines (160 loc) · 4.91 KB
/
test-server.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const DEBUG = false;
const fs = require('fs');
const resolve = require('path').resolve;
const url = require('url');
const createServer = require('http').createServer;
const express = require('express');
const bodyParser = require('body-parser');
const compression = require('compression');
const cookieParser = require('cookie-parser');
function log(...args) {
if (DEBUG) {
// eslint-disable-next-line no-console
console.log(...args);
}
}
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
function interpol(str, req) {
const interpolPrefix = '{req.';
const interpolStartIndex = str.indexOf(interpolPrefix);
if (interpolStartIndex !== -1) {
const interpolEndIndex = str.indexOf('}', interpolStartIndex + interpolPrefix.length);
if (interpolEndIndex === -1) {
return str;
}
const attribute = str.substring(interpolStartIndex + interpolPrefix.length, interpolEndIndex);
if (req[attribute] !== undefined) {
return str.replace(`${interpolPrefix}${attribute}}`, req[attribute]);
}
return str;
}
return str;
}
function normalizePath(path) {
return resolve(path).replace(/[/]{1,}/g, '/');
}
(function createApp(port = 3000) {
const app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(compression());
app.use(cookieParser());
// Accept request to mock a particular endpoint dynamically
let requests = {};
let fileIndex = {};
let mocks = {};
app.post('/mock', async (request, response) => {
log('MOCK', JSON.stringify(request.body));
const { path, result, headers, directories, status, timeout } = request.body;
let endpoint = path;
if (directories) {
directories.forEach((dir) => {
const fullDir = `${__dirname}/../${dir}`;
log('READ', fullDir, dir);
fs.readdir(fullDir, (err, files) => {
if (err) {
log('ERR', err);
}
if (!files) {
log('EMPTY DIR', fullDir);
return;
}
files.forEach((file) => {
const fullRequestPath = normalizePath(`${path}/${file}`);
const fullResourcePath = normalizePath(`${fullDir}/${file}`);
log('FILE', fullRequestPath, fullResourcePath);
fileIndex[fullRequestPath] = fullResourcePath;
});
});
});
if (!endpoint.endsWith('/')) {
endpoint += '/';
}
endpoint += '*';
} else {
mocks[path] = {
headers,
result,
status,
timeout,
};
}
log('REGISTER', endpoint);
response.end(JSON.stringify({ status: 'OK' }));
});
app.all('/info', (request, response) => {
log('/info');
response.end(JSON.stringify(requests));
});
app.all('/reset', async (request, response) => {
log('/reset');
requests = {};
fileIndex = {};
mocks = {};
response.end('{}');
});
// Listen to everything and dispatch to known mocks
app.all('/*', async (req, res) => {
const path = req.path;
const requestObj = clone({
baseUrl: req.baseUrl,
body: req.body,
cookies: req.cookies,
headers: req.headers,
hostname: req.hostname,
method: req.method,
originalUrl: req.originalUrl,
params: req.params,
path: req.path,
protocol: req.protocol,
query: req.query,
queryString: url.parse(req.url).query,
url: req.url,
xhr: req.xhr,
});
if (!requests[path]) {
requests[path] = [];
}
log('New request', path, requestObj);
if (mocks[path] !== undefined) {
// Keep track of requests seen
requests[path].push(requestObj);
const { headers, result, status, timeout } = mocks[path];
if (timeout) {
await new Promise(resolveTimeout => setTimeout(resolveTimeout, timeout));
}
// Set resulting headers
(headers || []).forEach(({ name, value }) => {
const finalValue = interpol(value, requestObj);
log('HEADER', name, finalValue);
res.header(name, finalValue);
});
// Set resulting status
if (status) {
res.status(status);
}
if (result === '{Transparent.gif}') {
log('Serve transparent gif');
res.header('Content-Type', 'image/gif');
res.end(new Buffer([71, 73, 70, 56, 57, 97, 1, 0, 1, 0, 128, 0, 0,
0, 0, 0, 255, 255, 255, 33, 249, 4, 1, 0, 0, 0, 0, 44, 0, 0, 0, 0, 1,
0, 1, 0, 0, 2, 1, 68, 0, 59]), 'binary');
} else {
log('Serve pre-registered response');
res.end(interpol(result, requestObj));
}
} else if (fileIndex[path] !== undefined) {
// Keep track of requests seen
requests[path].push(requestObj);
const finalPath = fileIndex[path];
log('Serve file from', finalPath);
res.sendFile(finalPath);
} else {
log('Not found', path);
res.status(404).send('Not found');
}
});
createServer(app).listen(port);
}());