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

@assassinonz/exzodus-router

v0.0.16

Published

Express router wrapper with end to end type safety

Downloads

306

Readme

ExZodus

ExZodus provides a type-safe Axios client wrapper and an Express router with auto-completion features backed by Zod schemas. This project is heavily inspired by the Zodios project.

Why ExZodus?

The existence of this project is due to following factors.

  • The wrappers provided by the Zodios project caused heavy TS-Server performance issues leading to Type instantiation is excessively deep and possibly infinite.ts(2589) errors.
  • The api definition structure required by Zodios seems limited.

Can this replace Zodios?

Absolutely not.

  • If your workflow didn't encounter above mentioned problems, you should definitely use Zodios. It is well documented and established.

  • Zodios has many more features that won't be included in the scope of this project.

How to use?

1. Installation

npm i @assassinonz/exzodus

2. Schema definition

  • Use @kubb/swagger-zod to generate the API schema using an openapi.yaml file or hand write it.

  • The API schema is typed as follows.

type Path = string;
type Method = string;
type Api = Record<Path, Record<Method, {
    request: z.ZodType | undefined;
    parameters: {
        path: z.ZodType | undefined;
        query: z.ZodType | undefined;
        header: z.ZodType | undefined;
    };
    responses: Record<number | "default", z.ZodType>;
    errors: Record<number, z.ZodType>;
}>>;
  • An example schema looks as follows.
export const paths = {
    "/users/:id": {
        get: {
            request: undefined,
            parameters: {
                path: z.object({ "id": z.coerce.number.int() }),
                query: undefined,
                header: undefined
            },
            responses: {
                200: z.object({ "id": z.number.int(),  "name": z.string() }),
                404: z.object({ "message": z.string() })
                default: z.object({ "id": z.number.int(),  "name": z.string() })
            },
            errors: {
                404: z.object({ "message": z.coerce.string() })
            }
        },
    }
}

3. Using ExZodusRouter

import { paths } from "../../kubb/zod/operations.js";
import { express, ExZodusRouter } from "@assassinonz/exzodus-router";

//Define context if needed
type Context = {
    userId: number;
}

//                    @kubb/swagger-zod generated API schema
//                                        ▼
const router = ExZodusRouter.new<typeof paths, Context>(paths, {
    //Provide error handler for Zod errors
    errorHandler: (err, req, res) => {
        //TODO: Handle errors
    },

    //Enable response validation to prevent unintentional data leaks
    attachResponseValidator: true
});


//  auto-complete path  fully typed and validated input params (body, query, params)
//             ▼           ▼    ▼
router.get("/users/:id", (req, res) => {
    if (req.ctx === undefined) {
        //Allows only documented response codes
        //Response is typed from the body of 404 response
        //                 ▼
        return res.status(404).json({
            message: "Please login first"
        });
    } else {
        const user = findUserById(req.ctx.userId);

        //Response is typed from the body of 200 response
        //                 ▼
        return res.status(200).json({
            id: user.id,
            name: user.name,
            password: user.password
        });
    }

});


const app = express();
app.use(express.json());
app.use("/api/v1", router);

4. Using ExZodusClient

Calling this API is now easy and has builtin autocomplete features :

import { paths } from "../../kubb/zod/operations.js";
import { ExZodusClient } from "@assassinonz/exzodus-client";


//                @kubb/swagger-zod generated API schema
//                                 ▼
const client = new ExZodusClient(paths, "http://localhost:8080/api/v1");


//   typed                auto-complete path   auto-complete params
//     ▼                           ▼                   ▼
const userResponse = await client.get("/users/:id", { path: { id: 7 } });
console.log(userResponse.data);

5. Output

This should output the following. Note the missing password field due to the attachResponseValidator option.

{
    id: 7,
    name: "John Doe"
}