@lomray/microservice-gateway
Version:
Gateway microservice based on NodeJS & inverted json.
44 lines (40 loc) • 1.42 kB
JavaScript
;
var tslib = require('tslib');
var microserviceHelpers = require('@lomray/microservice-helpers');
var remote = require('../config/remote.js');
/**
* Handles webhooks from other services
*/
const webhook = () => (req, res, next) => tslib.__awaiter(void 0, void 0, void 0, function* () {
const { url, method, body, headers, query } = req;
const { webhookUrl } = yield remote();
if (!webhookUrl) {
microserviceHelpers.Log.error('Webhook url is not provided');
return res.status(500).json({ error: 'Webhook url is not provided.' });
}
if (!['post', 'get'].includes(method.toLowerCase())) {
microserviceHelpers.Log.error('Method not allowed.');
return res.status(405).json({ error: 'Method not allowed.' });
}
const { groups } = new RegExp(`${webhookUrl}(?<methodUrl>[^/]+)/?(?<authToken>[^/?]+)?`).exec(url) ||
{};
if (!groups) {
next();
return;
}
const { methodUrl, authToken } = groups;
req.url = '/';
req.method = 'post';
req['forceStatus'] = true; // set response error status
headers.authorization = authToken ? `Bearer ${authToken}` : undefined;
req.body = {
method: methodUrl,
params: {
body,
rawBody: req['rawBody'],
query: query !== null && query !== void 0 ? query : {},
},
};
next();
});
module.exports = webhook;