0.6.1 • Published 2 years ago
use-openapi v0.6.1
use-openapi
Generate operations from openapi object.
The operation will:
- mount to a lots of node.js web framework(e.g. express/koa/fastify)
- validate the request with schema generated from openapi
Usage
Express
const app = express();
const { getOperations } = require("use-openapi");
const spec = require("./openapi.json");
const operations = getOperations(spec);
app.use(bodyParser.json());
operations.forEach(operation => {
/**
* A exmpale operation object
* {
* method: "put",
* operationId: "updatePet",
* path: "/pet",
* security: [
* {
* "petstore_auth": [
* "write:pets",
* "read:pets",
* ],
* },
* xProps: {
* "x-swagger-operationr-controller": "OrderController" ,
* },
* }
*/
const middlewares = [];
// apply security middleward
const auth_config = operation.security.find(v => v["petstore_auth"]);
if (auth_config) middlewares.push(auth(auth_config))
// mount operation
app[operation.method](operation.path, ...middlewares, (req, res, next) => {
// validate with the schema generated by openapi
const errors = operation.validate(getValidateData(req));
if (errors) {
res.status(405).json({ errors });
}
})
})
function getValidateData(req) {
const { headers, params, query, body } = req;
return { headers, params, query, body };
}