I am trying to replace the existing swagger tools in my project with oas-tools.
Source code shown as follows
const express = require('express');
const swaggerTools = require('swagger-tools');
const oasTools = require('oas-tools');
const { errorHandler } = require('errorHandlerPackage');
/**
* takes paths to controllers folder and swagger route config file and returns swagger router
* @method swaggerMiddleware
* @param {config.swaggerDoc} - path to the swagger api spec json/yaml
* @param {config.controllers} - path to the folder containing the controllers associated
* to above swagger api spec json/yaml
* @param {config.useOasTools} - bool, optional, a flag to determine if oas-tools is used or not
* @returns swagger router associated to the paths in the swaggerDoc
*/
const swaggerRouterFactory = ({ controllers, swaggerDoc, useOasTools }) => {
const router = express.Router({ mergeParams: true });
const options = {
controllers,
useStubs: true
};
const _addCustomizedPropToRequest = () => {
router.use((req, res, next) => {
const { a, b } = req.headers;
req.a = a;
req.b = b;
next();
});
}
const _addSwaggerSettings = (middleware) => {
router.use(middleware.swaggerMetadata());
router.use(middleware.swaggerValidator());
router.use(middleware.swaggerRouter(options));
router.use(middleware.swaggerUi());
router.use(errorHandler);
}
if (useOasTools) {
oasTools.configure({
controllers,
strict: true,
})
oasTools.initializeMiddleware(swaggerDoc, router, (middleware) => {
oasTools.initializeMiddleware(swaggerDoc, router, (middleware) => _addCustomizedPropToRequest());
_addSwaggerSettings(middleware);
});
return router;
}
swaggerTools.initializeMiddleware(swaggerDoc, (middleware) => {
swaggerTools.initializeMiddleware(swaggerDoc, (middleware) => _addCustomizedPropToRequest());
_addSwaggerSettings(middleware);
});
return router;
};
module.exports = swaggerRouterFactory;
I can get the req.a
and the req.b
when I called my API through swagger-tools, but when I tried to call the API through oas-tools, I got undefined
for the a
and b
. According to the oas-tools doc, to migrate from swagger-tools to oas-tools, I only need to pass the app as the second parameter to use the initializeMiddleware
function. But this seems doesn't work for the _addCustomizedPropToRequest
, the router.use(middleware.swaggerRouter(options))
works well.
Could anyone tell me what have I missed?