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

@oliver_nexro/zod_api

v0.8.0

Published

Configure API clients using Zod schemas for type-safety and interpreted action methods.

Downloads

973

Readme

zod_api

Configure strongly typed API clients and endpoints using Zod schemas.

Client

import { client, resource } from "zod_api"

const apiClient = client({
  baseUrl: "https://someapi.com/v1",
  resources: {
    foo: resource("/foo", {
      actions: {
        get: {
          dataSchema: z.object({
            bar: z.string(),
            baz: z.number(),
          }),
        },
      },
    }),
    bar: resource("/bar/:id", {
      // URL parameters schema is enforced by the given path, /baz/[id] pattern is also supported
      urlParamsSchema: z.object({
        id: z.number(),
      }),
      actions: {
        post: {
          searchParamsSchema: z.object({
            q: z.string().optional(),
          }),
          bodySchema: z.object({
            field1: z.string(),
            field2: z.number(),
          }),
          headersSchema: z.object({
            "x-key": z.string(),
            "x-secret": z.string(),
          }),
        },
      },
    }),
  },
})

Action methods are inferred and explorable through auto-complete:

const response1 = await apiClient.foo.get()

const resposne2 = await apiClient.bar.post({
  urlParams: {
    id: 123,
  },
  searchParams: {
    q: "query",
  },
  body: {
    field1: "some string",
    field2: 42,
  },
  headers: {
    "x-key": "key",
    "x-secret": "secret",
  },
})

Setup authentication:

import { z } from "zod"
import {
  ApiKeyAuth,
  BasicAuth,
  BearerTokenAuth,
  client,
  resource,
} from "./mod.ts"

// Schemas
const ArtistSchema = z.object({
  genres: z.array(z.string()),
  href: z.string(),
  id: z.string(),
  name: z.string(),
  popularity: z.number(),
  type: z.enum(["artist"]),
  uri: z.string(),
})

const AccessTokenSchema = z.object({
  access_token: z.string(),
  token_type: z.enum(["Bearer"]),
  expires_in: z.number(),
})

// Spotify API Client
const spotifyApiClient = client({
  baseUrl: "https://api.spotify.com/v1",
  logger: console,
  fetcher: fetch,

  // Setup authentication headers directly
  requestParams: {
    headers: {
      "x-api-key": "{api_key}",
    },
  },

  // API key authentication
  auth: new ApiKeyAuth({ key: "{api_key}" }),

  // Basic authentication
  auth: new BasicAuth({
    id: "{api_id}",
    secret: "{api_secret}",
  }),

  // Bearer token authentication
  auth: new BearerTokenAuth(AccessTokenSchema, {
    tokenUrl: "https://accounts.spotify.com/api/token",
    clientId: "{client_id}",
    clientSecret: "{client_secret}",
    mapper: (token) => token.access_token,
    requestParams: {
      body: new URLSearchParams({
        grant_type: "client_credentials",
      }),
    },
  }),

  // Define resources
  resources: {
    artists: resource("/artists/:id", {
      urlParamsSchema: z.object({
        id: z.string(),
      }),
      actions: {
        get: {
          dataSchema: ArtistSchema,
        },
      },
    }),
  },
})

Server (Deno specific)

Create a server with strongly typed endpoints:

import { resource } from "zod_api"
import { serve } from "zod_api/ext/serve"

serve({
  // Set options (optional)
  options: {
    hostname: "localhost",
    port: 3000
  },

  // Create middleware (optional)
  middleware: (req) => console.log(req.url)

  // Define resources
  resources: {
    foo: resource("/foo/:id", {
      urlParamsSchema: z.object({
        id: z.string(),
      }),
      actions: {
        get: {
          searchParams: z.object({
            q: z.number(),
          }),
          dataSchema: z.object({
            bar: z.string(),
            baz: z.number(),
          })
        }
      }
    })
  }
}, {
  foo: {
    // ctx contains parsed body, headers, url and search parameters.
    get: (req, ctx) => {
      // Return successful response
      return {
        ok: true,
        data: {
          bar: ctx.urlParams.id,
          baz: ctx.searchParams.q,
        }
      }

      // or return error
      return {
        ok: false,
        status: 401,
        message: "Unauthorized"
      }
    }
  }
})

Client & Server (Deno specific)

When you want to configure both the client and the server for maximum synchronization, you can do it the following way:

import { client, config, resource } from "zod_api"
import { serve } from "zod_api/ext/serve"

// in config.ts
const apiConfig = config({
  resources: {
    foo: resource("/foo", {
      // ...
    }),
  },
})

// in client.ts
const apiClient = client({
  ...apiConfig,
  baseUrl: "https://apihost.com",
})

// in server.ts
serve({
  ...apiConfig,
}, {
  foo: {
    // ...
  },
})