2021-02-04 19:15:23 +01:00
|
|
|
import handlers from './handlers';
|
2020-09-18 20:55:05 +02:00
|
|
|
|
|
|
|
const handlerMap = handlers.reduce((map, handler) => {
|
2020-12-02 17:49:49 +01:00
|
|
|
for (const methodName of handler.methodNames) {
|
2021-02-04 19:15:23 +01:00
|
|
|
map.set(methodName, handler.implementation);
|
2020-12-02 17:49:49 +01:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
return map;
|
|
|
|
}, new Map());
|
2020-09-18 20:55:05 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns a middleware that implements the RPC methods defined in the handlers
|
|
|
|
* directory.
|
|
|
|
*
|
|
|
|
* The purpose of this middleware is to create portable RPC method
|
|
|
|
* implementations that are decoupled from the rest of our background
|
|
|
|
* architecture.
|
|
|
|
*
|
|
|
|
* Handlers consume functions that hook into the background, and only depend
|
|
|
|
* on their signatures, not e.g. controller internals.
|
|
|
|
*
|
|
|
|
* Eventually, we'll want to extract this middleware into its own package.
|
|
|
|
*
|
|
|
|
* @param {Object} opts - The middleware options
|
|
|
|
* @param {Function} opts.sendMetrics - A function for sending a metrics event
|
|
|
|
* @returns {(req: Object, res: Object, next: Function, end: Function) => void}
|
|
|
|
*/
|
2020-11-03 00:41:28 +01:00
|
|
|
export default function createMethodMiddleware(opts) {
|
|
|
|
return function methodMiddleware(req, res, next, end) {
|
2020-09-18 20:55:05 +02:00
|
|
|
if (handlerMap.has(req.method)) {
|
2021-02-04 19:15:23 +01:00
|
|
|
return handlerMap.get(req.method)(req, res, next, end, opts);
|
2020-09-18 20:55:05 +02:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
return next();
|
|
|
|
};
|
2020-09-18 20:55:05 +02:00
|
|
|
}
|