From 3e8d540bd652bd0252590a0daa8867401d66f462 Mon Sep 17 00:00:00 2001 From: Amine Berrichi Date: Mon, 16 Aug 2021 18:58:29 +0200 Subject: [PATCH] Add middlewares to the config. (This can be useful if you want to process some treatment after the body-parser.) --- src/server.js | 1 + src/worker.js | 20 +++++++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/server.js b/src/server.js index 1d96723..c5b2441 100644 --- a/src/server.js +++ b/src/server.js @@ -25,6 +25,7 @@ const defaultConfig = { files: [], logger: {}, plugins: [], + middlewares: [], port: 8080, host: '0.0.0.0', processJobsConcurrent: true, diff --git a/src/worker.js b/src/worker.js index 59db4fd..984057e 100644 --- a/src/worker.js +++ b/src/worker.js @@ -3,13 +3,26 @@ import bodyParser from 'body-parser'; import './environment'; import logger from './utils/logger'; import renderBatch from './utils/renderBatch'; -import { runAppLifecycle, errorSync, raceTo } from './utils/lifecycle'; +import { errorSync, raceTo, runAppLifecycle } from './utils/lifecycle'; import BatchManager from './utils/BatchManager'; const attachMiddleware = (app, config) => { app.use(bodyParser.json(config.bodyParser)); }; +const attachMiddlewares = (app, config) => { + attachMiddleware(app, config); + + const { middlewares } = config; + if (Array.isArray(middlewares)) { + middlewares.forEach((middleware) => { + if (typeof middleware === 'function') { + app.use(middleware); + } + }); + } +}; + const attachEndpoint = (app, config, callback) => { app.post(config.endpoint, renderBatch(config, callback)); }; @@ -117,8 +130,8 @@ const initServer = (app, config, callback) => { }; const worker = (app, config, onServer, workerId) => { - // ===== Middleware ========================================================= - attachMiddleware(app, config); + // ===== Middlewares ========================================================= + attachMiddlewares(app, config); if (onServer) { onServer(app, process); @@ -154,6 +167,7 @@ const worker = (app, config, onServer, workerId) => { }; worker.attachMiddleware = attachMiddleware; +worker.attachMiddlewares = attachMiddlewares; worker.attachEndpoint = attachEndpoint; worker.initServer = initServer; worker.Server = Server;