npm.io
1.0.3 • Published 2 years ago

express-openapi-typescript

Licence
ISC
Version
1.0.3
Deps
0
Size
59 kB
Vulns
0
Weekly
0

express-openapi-typescript

Utilities for adding types to express routes according to an OpenAPI specification.

Install

npm install express-openapi-typescript openapi-typescript

Usage

Generate types

Use openapi-typescript to generate the types file containing the paths interface:

npx openapi-typescript ./path/to/my/schema.yaml -o ./path/to/my/schema.d.ts

Note: Only "application/json" content types are supported currently.

Typed router

The recommended method is wrapping an express Router with an OpenApiRouter. The delete, get, patch, post, and put methods will be typed according to the fully qualified (openapi) route that is passed in as a type parameter:

import express, { json, Router } from "express";
import { OpenApiRouter } from "express-openapi-typescript";

import { paths } from "./path/to/my/schema.d.ts";

const app = express();

app.use(json());

const router = OpenApiRouter<paths>(Router());

// Route corresponding to 'POST /pet' path in openapi spec
router.post<"/pet">("/", (req, res) => {
  // req.body, req.query, req.params, and res.json() are fully typed
  res.json({
    name: req.body.name,
    photoUrls: req.body.photoUrls,
  });
});

// The original Router() instance is stored in `router` property
app.use("/pet", router.router);

Note that the express route is relative to the router, and so may not be the exact same as the router.

Typed request handlers

The same functionality can be acheived without extending the router, which may be required in some use cases, by casting the request handler functions themselves:

import express, { json, Router } from "express";
import {
  DeleteHandler,
  GetHandler,
  PatchHandler,
  PostHandler,
  PutHandler,
} from "express-openapi-typescript";

import { paths } from "./path/to/my/schema.d.ts";

const app = express();

app.use(json());

const router = Router();

router.post("/", ((req, res) => {
  // req.body, req.query, req.params, and res.json() are fully typed
  res.json({
    name: req.body.name,
    photoUrls: req.body.photoUrls,
  });
  // Route corresponding to 'POST /pet' path in openapi spec
}) as PostHandler<paths, "/pet">);

app.use("/pet", router);