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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@domain-first/handlers-rest

v6.0.0

Published

Expose domain operations through REST without coupling your domain to HTTP

Readme

Requirements

About

The API is intentionally small and fluent: describe transport → map to domain → describe response → map back. Describing a response is an optional step - by default all response go to the body, so the happy path stays minimal. Everything is strongly-typed. TypeScript checks the contract at compile time.

Adapters

Examples

Quick Start

import { createEndpoint } from "@domain-first/handlers-rest";
import { defineHandler } from "@domain-first/handlers";
/**
 * Any adapter can be used.
 */
import nextAdapter from "./adapters/next";
/**
 * Any Standard Schema compatible library fits.
 */
import z from "zod";

const sum = defineHandler({
    inputSchema: z.object({
        a: z.number(),
        b: z.number(),
    }),
    outputSchema: z.number(),
    handler: async ({ a, b }) => a + b,
});

const endpoint = createEndpoint();
const nextEndpoint = endpoint(nextAdapter);

const sumPOST = nextEndpoint(sum, {
    route: { method: "post", path: ["sum"] },
})
    /**
     * Describe input schemas.
     */
    .input((schema) => {
        return {
            body: schema,
        };
    })
    /**
     * Describe input mapping.
     */
    .mapInput((input) => ({
        a: input.body.a,
        b: input.body.b,
    }));

export const POST = sumPOST;

/**
 * POST /sum
 *
 * REQUEST BODY: { a: 10, b: 30 }
 * RESPONSE BODY: 40
 */

Endpoint contracts

To obtain an endpoint contract, use EndpointContract generic:

import type { EndpointContract } from "@domain-first/handlers-rest";

type SumPOSTContract = EndpointContract<typeof sumPOST>;

/**
type SumPOSTContract = {
    request: {
        body: { a: number; b: number; };
    };
    response: {
        body: number;
    };
}
 */

Context and error handling

import {
    type RawRequestModel,
    createEndpoint,
} from "@domain-first/handlers-rest";
import { defineHandler } from "@domain-first/handlers";
import z from "zod";
import adapter from "./adapter";

class UnauthorizedAccessError extends Error {}

/**
 * Context logic.
 */
const authContext = async (rawRequest: RawRequestModel) => {
    const bearerHeader = rawRequest.headers?.Authorization ?? "";

    if (!bearerHeader) {
        throw new UnauthorizedAccessError();
    }

    const token = bearerHeader.split(" ").pop();

    // some decoding logic
    const { userId } = await decodeToken(token);

    return { userId };
};

/**
 * Adding context in endpoint generator.
 */
const endpointWithAuth = createEndpoint({
    context: async (rawRequest) => {
        const auth = await authContext(rawRequest);

        return { auth };
    },
    errorStatuses: {
        401: {
            checks: [(x) => x instanceof UnauthorizedAccessError],
            description: "User is not logged in",
        },
    },
});

const nextEndpointWithAuth = endpointWithAuth(nextAdapter);

const greetUser = defineHandler({
    input: z.object({ authorId: z.string(), name: z.string() }),
    output: z.string(),
    handler: async ({ authorId, name }) => {
        return `Hello, ${name}! (from ${authorId})`;
    },
});

const greetUserEndpoint = nextEndpointWithAuth(greetUser, {
    route: { method: "get", path: ["users", "greet"] },
})
    .input((inputSchema) => ({
        query: inputSchema.pick({ name: true }),
    }))
    .mapInput((input) => {
        return {
            name: input.query.name,
            // strongly-typed
            authorId: input.context.auth.userId,
        };
    });

Defining custom output

const sumPATCH = nextEndpoint(sum, {
    route: { method: "patch", path: ["sum"] },
})
    .input((schema) => ({
        body: schema,
    }))
    .mapInput((input) => ({
        a: input.body.a,
        b: input.body.b,
    }))
    .output((schema) => ({
        body: z.object({
            result: schema,
        }),
    }))
    .mapOutput((output) => ({
        body: { result: output },
    }));

export const PATCH = sumPATCH;

OpenAPI generation

import { generateOpenAPI } from "@domain-first/handlers-rest";

const endpoints = [sumPOST, greetUserEndpoint, sumPATCH];

const openAPI = async () => {
    const openAPIDocument = generateOpenAPI(endpoints, {
        document: {
            info: { title: "Test API", version: "1.0.0" },
        },
        outputFile: { path: "openapi.json" },
        /**
         * If your Standard Schemas are not Standard JSON Schemas
         * out of the box, you can pass optional mapper in
         * `standardSchemaToJSONSchema` field
         */
    });
};