-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·62 lines (50 loc) · 1.58 KB
/
index.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
#! /usr/bin/env node
/**
* This is a pure-node mock API server implementation
* See below for options and api mock schema
* By default server will respond with status 200 and json content-type
*/
const http = require('http');
const { parseCLIOptions, loadMockApi, findMockKey } = require('./utils');
const watch = require('./watcher');
const config = {
port: 3000,
path: './mockApi.json',
};
const args = process.argv.slice(2);
parseCLIOptions(args, config);
const mockApi = loadMockApi(config.path);
console.log(`🧐 Loaded api from ${config.path}`);
watch(config.path, mockApi);
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
const { method, url } = req;
let key = '';
const parts = url.split('/').slice(1);
if (parts.length > 1) {
const roots = Object.keys(mockApi).filter(k => k.startsWith(`${method} /${parts[0]}`));
key = findMockKey(roots, parts);
} else {
key = url;
}
const data = mockApi[[method, key].join(' ')];
console.log(`👉 ${method} ${url}`);
if (data && data.response) {
if (data.status) {
res.statusCode = data.status;
}
if (data.headers) {
Object.entries(data.headers).forEach(([h, v]) => res.setHeader(h, v));
}
res.end(JSON.stringify(data.response));
} else {
res.status = 404;
console.log(`🤔 No response for ${method} ${url}`);
res.end(JSON.stringify({}));
}
});
server.listen(config.port, '127.0.0.1', () => {
console.log('🚀 Started server');
console.log(`🔗 http://localhost:${config.port}`);
});