0.6.1 • Published 2 years ago

use-openapi v0.6.1

Weekly downloads
2
License
MIT
Repository
github
Last release
2 years ago

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 };
}
0.5.0

2 years ago

0.6.1

2 years ago

0.6.0

2 years ago

0.3.8

3 years ago

0.4.0

3 years ago

0.3.6

4 years ago

0.3.4

4 years ago

0.3.3

4 years ago

0.3.2

4 years ago

0.3.0

4 years ago

0.2.0

4 years ago

0.1.8

4 years ago

0.1.6

4 years ago

0.1.4

4 years ago

0.1.0

4 years ago