npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@oselvar/openapi-validator

v0.3.1

Published

Validate OpenAPI requests and responses against Zod schemas

Downloads

12

Readme

This is a small library that validates HTTP requests and responses against an OpenAPI 3.0 specification.

It is designed to work with any web servers/framework that uses the Fetch API such as:

It also provides adapters for non-Fetch based web servers/frameworks such as:

The library is built on top of Zod and zod-to-openapi.

Installation

npm install --save @oselvar/openapi-validator

Define an OpenAPI route

import { RouteConfig } from '@asteasolutions/zod-to-openapi';
import { z } from 'zod';

import {
  Response404,
  Response415,
  Response422,
  Response500,
} from '@oselvar/openapi-validator';

// Define Zod schemas for the request parameters, query and body

const ThingParamsSchema = z.object({
  thingId: z.string().regex(/[\d]+/),
});

const ThingQuerySchema = z.object({
  thingId: z.string().regex(/[\d]+/).optional(),
});

const ThingBodySchema = z.object({
  name: z.string().regex(/[a-z]+/),
  description: z.string().regex(/[a-z]+/),
});

// Define an OpenAPI route using https://github.com/asteasolutions/zod-to-openapi

const routeConfig: RouteConfig = {
  method: 'post',
  path: '/things/{thingId}',
  request: {
    params: ThingParamsSchema,
    query: ThingQuerySchema,
    body: {
      content: {
        'application/json': {
          schema: ThingBodySchema,
        },
      },
    },
  },
  responses: {
    200: {
      description: 'Create a thing',
      content: {
        'application/json': {
          schema: ThingBodySchema,
        },
      },
    },
    404: Response404,
    415: Response415,
    422: Response422,
    500: Response500,
  },
};

Create a validator

The Validator class uses the schemas in the routeConfig object to validate requests and responses.

import { Validator } from '@oselvar/openapi-validator';

const validator = new Validator(routeConfig);

Validate requests and responses

Your web server will provide a request object and a params object.

(If your web server does not use the Fetch API, see the Adapters section below.)

const request: Request = ...;
const params: Record<string, string | undefined> = ...;

const params = validator.params<z.infer<typeof ThingParamsSchema>>(params);
const body = await validator.body<z.infer<typeof ThingBodySchema>>(request);
const response = validator.validate(Response.json(body));

Error handling

The methods on the Validator object will throw a ValidationError if the request or response is invalid. You must handle this error and return an appropriate HTTP response to the client.

We recommend doing this in a middleware function. Please refer to your web server's documentation for more information.

Here is an example:

import { unwrapError } from '@oselvar/openapi-validator';

try {
  // Run the handler
} catch (error) {
  const { message, response } = unwrapError(error);
  console.error(response.status, message);
  return response;
}

Adapters

If you are using a framework that does not use the Fetch API Request and Response objects such as AWS Lambda, Express or Fastify, use the FetchRoute type to define your handler function:

import { FetchRoute, Validator } from '@oselvar/openapi-validator';
import { RouteConfig } from '@asteasolutions/zod-to-openapi';
import { z } from 'zod';

const routeConfig: RouteConfig = { ... };
const validator = new Validator(routeConfig);

const fetchRoute: FetchRoute = async (context) => {
  const params = validator.params<z.infer<typeof ThingParamsSchema>>(context.params);
  const body = await validator.body<z.infer<typeof ThingBodySchema>>(context.request);
  return validator.validate(Response.json(body));
};

Note that the support for multiple HTTP servers can also simplify your developer experience. You can write your handler function once and then register it with multiple HTTP servers.

For example, you can register your handler functions with Express or Fastify during development and then register them with AWS Lambda during production.

The next step is to convert the FetchRoute to a function that can be registered with your HTTP server.

AWS Lambda

import { FetchOpenAPIHandler } from '@oselvar/openapi-validator';
import { toProxyHandler } from '@oselvar/openapi-validator/aws-lambda';

export const handler = toProxyHandler(fetchRoute);

Express

Coming soon.

Fastify

Coming soon.