New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@danprince/zhttp

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@danprince/zhttp

Typesafe HTTP endpoints with express, zod, and static-path

  • 0.0.6
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

zhttp

A small library that brings zod, express, and static-path together to create type safe HTTP endpoints for clients and servers.

Getting Started

Install zhttp and its peer dependencies.

npm i @danprince/zhttp express @types/express zod static-path

Example

Define your endpoints somewhere that both your client and server can import from.

// shared/endpoints.ts
import { endpoint } from "@danprince/zhttp";
import { z } from "zod";
import { path } from "path";

export let sendMessage = endpoint({
  // static-path definition
  path: path("/message/:to"),

  // "post" | "get" | "patch" | "put" | "delete" | "head"
  method: "post",

  // zod request body schema
  request: z.object({
    subject: z.string(),
    text: z.string(),
  }),

  // zod response body schema
  response: z.object({
    status: z.union([
      z.literal("success"),
      z.literal("pending"),
      z.literal("failure"),
    ]),
  }),
});

Then create corresponding server side route handlers.

// server/routes.ts
import { createRouter } from "@danprince/zhttp/express";
import { sendMessage } from "../shared/endpoints";

let router = createRouter();

router.use(sendMessage, async (req, res) => {
  // Type safe access from req.body
  let { subject, text } = req.body;

  // ...

  // Type safe res.body methods
  res.json({ status: "success" });
});

// router.routes() is an Express.Router

And finally, the client side.

// client/index.ts
import { fetchJson } from "@danprince/zhttp/fetch";
import { sendMessage } from "../shared/endpoints";

let res = await fetchJson(sendMessage, {
  params: { to: "howard" },
  body: {
    subject: "Hello!",
    text: "This is a message",
  },
});

// Type safe response
res.status

FAQs

Package last updated on 14 Nov 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc