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

openapi-express

v0.0.7

Published

Typesafe Express Router wrapper supporting OpenAPI types

Downloads

113

Readme

Status: Experimental

openapi-express is a typesafe Express Router wrapper supporting OpenAPI types.

  • Typesafe: Build with TypeScript for strong type safety and support for openapi-typescript types
  • Validation: Ensures request validation against defined schemas using zod

Motivation

Provide a typesafe, straightforward, and lightweight wrapper for the Express Router that seamlessly integrates with OpenAPI schemas using openapi-typescript. It aims to simplify error handling and request validation.

📖 Usage

1. Generate TypeScript Definitions

Use openapi-typescript to generate TypeScript definitions from your OpenAPI schema.

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

More info

2. Create an OpenAPI Router

Import the generated paths and use createOpenApiRouter() to create an OpenAPI router.

router.ts

import { createOpenApiRouter } from 'openapi-express';
import { paths } from './openapi-paths'; // Import generated paths

export const router: Router = Router();
export const openApiRouter = createOpenApiRouter<paths>(router);

3. Use the Router in an Express App

Integrate the OpenAPI router into your Express application to handle requests. Use express.json() middleware to parse incoming JSON requests.

app.ts

import express from 'express';
import { router } from './router';

const app = express();

app.use(express.json()); // For parsing application/json

app.use('/', router);

4. Define the Endpoints with Full Type Safety

Define your API endpoints with full type safety and request validation using Zod. TypeScript provides type safety at compile time, but runtime validation is necessary to ensure incoming requests meet the expected structure and types. Zod helps with this by providing a schema-based validation mechanism. If a schema is invalid, a ValidationError is thrown.

routes/posts.ts

import { Router } from 'express';
import { z } from 'zod';
import { openApiRouter } from '../router';

const posts = [
    { id: '1', title: 'First Post', content: 'This is the first post.' },
    { id: '2', title: 'Second Post', content: 'This is the second post.' }
];

// Get all posts
openApiRouter.get(
    '/posts',
    {},
    async (req, res) => {
        res.json(posts);
    }
);

// Get a post by ID
openApiRouter.get(
    '/posts/{id}',
    {
        pathSchema: {
            id: z.string()
        }
    },
    async (req, res) => {
        const post = posts.find(p => p.id === req.params.id);
        if (post) {
            res.json(post);
        } else {
            res.status(404).json({ message: 'Post not found' });
        }
    }
);

// Create a new post
openApiRouter.post(
    '/posts',
    {
        bodySchema: z.object({
            title: z.string(),
            content: z.string()
        })
    },
    async (req, res) => {
        const newPost = {
            id: (posts.length + 1).toString(),
            ...req.body
        };
        posts.push(newPost);
        res.status(201).json(newPost);
    }
);