forked from mustafar/parrot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
178 lines (158 loc) · 5.15 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
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
import httpStatus from 'http-status-codes';
import { findKey, get as getOrDefault, isEmpty } from 'lodash';
import JSum from 'jsum';
import querystring from 'querystring';
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const swaggerMiddleware = require('swagger-express-middleware');
const interceptor = require('express-interceptor');
const app = express();
const port = process.env.PORT;
const swaggerPath = process.env.SWAGGER_SPEC;
const isVerboseMode = process.env.VERBOSE !== undefined;
// eslint-disable-next-line
const getQueryHash = (query) => isEmpty(query) ? '' : JSum.digest(query, 'SHA256', 'hex');
const setRequestStatus = (res, code) => {
// this is a hack to overwrite the message set by the swagger middleware
// (which is not overwritten by res.status(204).send('Not Implemented'), etc )
res.statusMessage = httpStatus.getStatusText(code);
res.status(code);
return res;
};
let mocks = {};
const resetMocks = () => { mocks = {}; };
const mockKey = (method, path) => `${method.toUpperCase()} ${path}`;
const saveMock = (mockBehavior) => {
const {
method, path, status, response, qs,
} = mockBehavior;
if (method === undefined ||
path === undefined ||
!/^\//.test(path) ||
status === undefined) {
throw new Error('invalid mock behavior supplied');
}
const mockResponse = { status };
if (response !== undefined) {
mockResponse.response = response;
}
const queryHash = getQueryHash(querystring.parse(qs));
mocks[mockKey(method, `${path}${queryHash}`)] = mockResponse;
};
const getMockResponse = (method, path, query) => {
const queryHash = getQueryHash(query);
const key = mockKey(method, `${path}${queryHash}`);
const mockResponse = mocks[key];
if (isVerboseMode) {
/* eslint-disable no-console */
console.log('---------------------');
console.log(`mocked keys: [ ${Object.keys(mocks)} ]`);
console.log(`requested key: ${key}`);
/* eslint-enable no-console */
}
return mockResponse;
};
const handle = (req, res) => {
// get swagger basePath
const basePath = getOrDefault(req, 'swagger.api.basePath', '')
.replace(/\/$/, '');
if (getOrDefault(req, 'statusOverride')) {
setRequestStatus(res, req.statusOverride).send().end();
}
if (!getOrDefault(req, 'swagger.api')) {
setRequestStatus(res, httpStatus.NOT_FOUND).send().end();
}
// get current request path
const path = req.path.substring(basePath.length);
// check for a mocking call
if (path === '/mock') {
if (req.method === 'DELETE') {
resetMocks();
} else if (req.method === 'PUT') {
saveMock(req.body);
} else {
res.status(501).send('Not Implemented').end();
return;
}
setRequestStatus(res, httpStatus.NO_CONTENT).send().end();
return;
}
// check for an invalid path
if (req.swagger.path === null || req.swagger.path === undefined) {
setRequestStatus(res, httpStatus.NOT_FOUND).send().end();
return;
}
// checked for mocked bhavior
const mockedResponse = getMockResponse(req.method, path, req.query);
if (mockedResponse) {
res.status(mockedResponse.status);
if (mockedResponse.response !== undefined) {
res.send(mockedResponse.response);
}
res.end();
return;
}
// check for default behavior
const { responses } = req.swagger.path[req.method.toLowerCase()];
const exampleResponseHttpCode = findKey(responses, r => getOrDefault(r, 'schema.example') !== undefined);
if (exampleResponseHttpCode !== undefined) {
res.send(responses[exampleResponseHttpCode].schema.example).end();
return;
}
setRequestStatus(res, httpStatus.NOT_IMPLEMENTED).send().end();
};
if (port === undefined || swaggerPath === undefined) {
throw new Error('PORT and SWAGGER_SPEC environment variables must be set.');
}
fs.stat(swaggerPath, (err) => {
if (err) {
throw new Error('swagger spec not found');
}
});
const swaggerInterceptor = interceptor((req, res) => ({
isInterceptable: () => true,
intercept: () => {
try {
handle(req, res);
} catch (err) {
console.log(err); // eslint-disable-line no-console
setRequestStatus(res, httpStatus.INTERNAL_SERVER_ERROR).send().end(); // Oops
}
},
}));
const errorMiddleware = (err, req, res, next) => {
if (err && err.message && !/mock$/.test(err.message)) {
console.log(err); // eslint-disable-line no-console
req.statusOverride = err.status;
next();
} else {
next();
}
};
swaggerMiddleware(swaggerPath, app, (err, middleware) => {
app.use(
swaggerInterceptor,
bodyParser.urlencoded({ extended: false }),
bodyParser.json(),
middleware.metadata(),
middleware.CORS(),
middleware.files(),
middleware.parseRequest(),
middleware.validateRequest(),
errorMiddleware,
middleware.mock(),
);
const server = app.listen(port, () => {
// eslint-disable-next-line no-console
console.log(`The mock api is now running at http://localhost:${port}`);
});
/* eslint-disable */
['SIGINT', 'SIGTERM'].forEach(function (signal) {
process.on(signal, function () {
console.log('Shutting down...');
server.close(process.exit);
});
});
/* eslint-enable */
});