-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
331 lines (300 loc) · 11.5 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/* eslint-disable consistent-return */
/* eslint-disable no-restricted-syntax */
/**
* An HTTP transport module for postmaster-general.
* @module index
*/
const bodyParser = require("body-parser");
const compression = require("compression");
const express = require("express");
const Promise = require("bluebird");
const _ = require("lodash");
const rp = require("request-promise");
const rpErrors = require("request-promise/errors");
const { Transport } = require("postmaster-general-core");
const { errors } = require("postmaster-general-core");
const defaults = require("./defaults");
/**
* A postmaster-general transport module using HTTP.
* @extends Transport
*/
class HTTPTransport extends Transport {
/**
* Constructor for the HTTPTransport object.
* @param {object} [options] - Optional settings.
* @param {number} [options.timingsResetInterval] - How frequently should the transport clear its timing metrics, in milliseconds.
* @param {number} [options.port] - The port that Express should listen on.
* @param {boolean} [options.serveGzip] - Whether or not the transport should use gzip for express.js responses.
* @param {boolean} [options.sendGzip] - Whether or not to use gzip for published messages.
*/
constructor(options = {}) {
super(options);
if (!_.isUndefined(options.port) && !_.isNumber(options.port)) {
throw new TypeError('"options.port" should be a number.');
}
if (!_.isUndefined(options.serveGzip) && !_.isBoolean(options.serveGzip)) {
throw new TypeError('"options.serveGzip" should be a boolean.');
}
if (!_.isUndefined(options.sendGzip) && !_.isBoolean(options.sendGzip)) {
throw new TypeError('"options.sendGzip" should be a boolean.');
}
/**
* The port that Express should listen on.
* @type {number}
*/
this.port = options.port || defaults.port;
/**
* Whether or not the transport should use gzip for express.js responses.
* @type {boolean}
*/
this.serveGzip = _.isUndefined(options.serveGzip) ? defaults.serveGzip : options.serveGzip;
/**
* Whether or not the transport should use gzip for published requests.
* @type {boolean}
*/
this.sendGzip = _.isUndefined(options.sendGzip) ? defaults.sendGzip : options.sendGzip;
this.app = express();
this.server = null;
// Turn on compression, if applicable.
if (this.serveGzip) {
this.app.use(compression());
}
// Make sure request bodies are automatically parsed into JSON.
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({ extended: false }));
// Register the router. We'll use this to swap out listeners on the fly.
this.router = express.Router(); // eslint-disable-line new-cap
this.app.use((req, res, next) => {
this.router(req, res, next);
});
// Catch 404s and forward to error handler.
this.app.use((req, res, next) => {
next(new errors.NotFoundError("Not Found"));
});
// Top-level error handler
// eslint-disable-next-line no-unused-vars
this.app.use((err, req, res, next) => {
// eslint-disable-next-line no-param-reassign
err.response = err.response || { message: err.message };
if (err instanceof errors.InvalidMessageError) {
res.status(400).json(err.response);
} else if (err instanceof errors.UnauthorizedError) {
res.status(401).json(err.response);
} else if (err instanceof errors.ForbiddenError) {
res.status(403).json(err.response);
} else if (err instanceof errors.NotFoundError) {
res.status(404).json(err.response);
} else {
res.status(500).json(err.response);
}
});
}
/**
* Disconnects the transport from any services it references.
* @returns {Promise}
*/
disconnect() {
return super.disconnect().then(() => {
if (this.server) {
return new Promise((resolve) => {
this.server.close(() => {
resolve();
this.server = null;
});
});
}
});
}
/**
* Processes a routing key into a format appropriate for the transport type.
* @param {string} routingKey - The routing key to convert.
* @returns {string}
*/
resolveTopic(routingKey) {
return super.resolveTopic(routingKey).replace(/:/g, "/");
}
/**
* Adds a new message handler.
* @param {string} routingKey - The routing key of the message to handle.
* @param {function} callback - The function to call when a new message is received.
* @param {object} [options] - Optional params for configuring the handler.
* @param {number} [options.method] - The HTTP method to listen for. Defaults to "GET".
* @returns {Promise}
*/
addMessageListener(routingKey, callback, options = {}) {
return super.addMessageListener(routingKey, callback, options).then((callbackWrapper) => {
// eslint-disable-next-line no-param-reassign
options.method = (options.method || "get").toLowerCase();
const topic = this.resolveTopic(routingKey);
// Generate the Express.js handler that wraps the callback function.
const handler = (req, res, next) => {
const msg = options.method === "get" || options.method === "delete" ? req.query : req.body;
callbackWrapper(msg, req.headers["x-pmg-correlationid"], req.headers["x-pmg-initiator"])
.then((response) => {
res.status(200).json(response || {});
})
.catch((err) => {
next(err || new errors.ResponseProcessingError("Unable to process response."));
});
};
switch (options.method) {
case "get":
this.router.get(`/${topic}`, handler);
break;
case "post":
this.router.post(`/${topic}`, handler);
break;
case "put":
this.router.put(`/${topic}`, handler);
break;
case "delete":
this.router.delete(`/${topic}`, handler);
break;
case "all":
this.router.all(`/${topic}`, handler);
break;
default:
throw new TypeError(`${options.method} is an unsupported method.`);
}
return handler;
});
}
/**
* Deletes a message handler.
* @param {string} routingKey - The routing key of the handler to remove.
* @returns {Promise}
*/
removeMessageListener(routingKey) {
return super.removeMessageListener(routingKey).then(() => {
const topic = this.resolveTopic(routingKey);
const newRouter = express.Router(); // eslint-disable-line new-cap
for (const handler of this.router.stack) {
if (handler.route.method) {
const method = handler.route.method.toLowerCase();
for (const layer of handler.route.stack) {
if (layer.path !== topic) {
switch (
method // eslint-disable-line max-depth
) {
case "get":
newRouter.get(layer.path, layer.handle);
break;
case "post":
this.router.post(layer.path, layer.handle);
break;
case "put":
this.router.put(layer.path, layer.handle);
break;
case "delete":
this.router.delete(layer.path, layer.handle);
break;
/* istanbul ignore next */
default:
newRouter.all(layer.path, layer.handle);
break;
}
}
}
}
}
this.router = newRouter;
});
}
/**
* Starts listening to messages.
* @returns {Promise}
*/
listen() {
return super.listen().then(() => {
return new Promise((resolve) => {
this.server = this.app.listen(this.port, () => {
resolve();
});
});
});
}
/**
* Publishes a fire-and-forget message that is not expected to return a meaningful response.
* @param {string} routingKey - The routing key to attach to the message.
* @param {object} [message] - The message data to publish.
* @param {object} [options] - Optional publishing options.
* @param {object} [options.correlationId] - Optional marker used for tracing requests through the system.
* @param {object} [options.initiator] - Optional marker used for identifying the user who generated the initial request.
* @returns {Promise}
*/
publish(routingKey, message, options) {
return this.request(routingKey, message, options).catch((err) => {
if (!(err instanceof errors.ResponseError)) {
throw err;
}
});
}
/**
* Publishes an RPC-style message that waits for a response.
* @param {string} routingKey - The routing key to attach to the message.
* @param {object} [message] - The message data to publish.
* @param {object} [options] - Optional publishing options.
* @param {object} [options.correlationId] - Optional marker used for tracing requests through the system.
* @param {object} [options.initiator] - Optional marker used for identifying the user who generated the initial request.
* @param {object} [options.headers] - Optional http headers to send as part of the request.
* @param {object} [options.host] - Optional http hostname to send to. If not specified, the routing key is assumed to include the hostname.
* @param {object} [options.port] - Optional port to send. Requires the options.host parameter to be set.
* @param {object} [options.protocol] - Http protocol to use (HTTP/HTTPS). Defaults to HTTP.
* @param {object} [options.method] - Http method to use. Defaults to GET.
* @returns {Promise}
*/
request(routingKey, message = {}, options = {}) {
return super.request(routingKey, message, options).then((correlationId) => {
const topic = this.resolveTopic(routingKey);
// eslint-disable-next-line no-param-reassign
options.headers = options.headers || {};
// eslint-disable-next-line no-param-reassign
options.headers["x-pmg-correlationid"] = correlationId;
// eslint-disable-next-line no-param-reassign
options.headers["x-pmg-initiator"] = options.initiator;
// Build the uri.
let uri;
if (options.host) {
uri = `${options.protocol || "http"}://${options.host}${
options.port ? `:${options.port}` : ""
}/${topic}`;
} else {
/* istanbul ignore next */
uri = `${options.protocol || "http"}://${topic}`;
}
// Configure the request.
const reqSettings = {
uri,
method: options.method || "GET",
headers: options.headers,
json: true,
gzip: this.sendGzip,
};
/* istanbul ignore next */
if (reqSettings.method === "GET") {
reqSettings.qs = message;
} else {
reqSettings.body = message;
}
return rp(reqSettings).catch((err) => {
if (err instanceof rpErrors.StatusCodeError) {
switch (err.statusCode) {
case 400:
throw new errors.InvalidMessageError(err.error.message, err.response.body);
case 401:
throw new errors.UnauthorizedError(err.error.message, err.response.body);
case 403:
throw new errors.ForbiddenError(err.error.message, err.response.body);
case 404:
throw new errors.NotFoundError(err.error.message, err.response.body);
default:
throw new errors.ResponseProcessingError(err.error.message, err.response.body);
}
}
/* istanbul ignore next */
throw new errors.RequestError(err);
});
});
}
}
module.exports = HTTPTransport;