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

@nystudio/nextapi-core

v0.1.1

Published

The Core of next-api

Downloads

132

Readme

next-api

next-api is a library that handles data validation of Nextjs Api Routes with the Zod library.

Requirement

  • Nextjs >= 15

Installation

// if you are using NextJS >= 15
npm i @nystudio/nextapi-core @nystudio/nextapi-router

// if you are using NextJS == 14
npm i @nystudio/nextapi-core@^0.0.9 @nystudio/nextapi-router@^0.0.9

Features

  • api router
  • openapi
  • circuit breaker

Basic usage

import { NextApiRouter } from '@nystudio/nextapi-router';

// file: ApiRouter.ts
export const routerSingleton = new NextApiRouter()

// file: /src/app/api/users/route.ts
import { routerSingleton } from 'ApiRouter';

export const POST = routerSingleton.apiRouter(
  async ({ request }) => {
    console.log("requested", request.data.name)
    return Promise.resolve({
      id: 12345,
      name: request.data.name,
    })
  },
  {
    validation: {
      data: z.object({
        name: z.string(),
      }),
      response: z.object({
        id: z.number().int().positive(),
        name: z.string(),
      }),
    },
  },
);

// file: /src/app/api/users/[userId]/route.ts
import { routerSingleton } from 'ApiRouter';

export const GET = routerSingleton.apiRouter(async ({ request }) => {
  ...
});

OpenApi

Here is how to use open api with next-api

Install the dependencies
npm i @nystudio/nextapi-openapi swagger-ui-react
Register a route

next-api registers routers in NextJS build time.

import { NextApiRouterOpenapiOption, nextApiStoreRouterOpenapiDocument } from "@nystudio/nextapi-openapi"

// file: ApiRouter.ts
const routerSingleton = new NextApiRouter<NextApiRouterOpenapiOption>() // <-- use openapi router type

routerSingleton.addEventListener("onRouteAdded", async (options) => {
  try {
    nextApiStoreRouterOpenapiDocument(options)
  } catch (error: unknown) {
    const err = error instanceof Error ? error : new Error("Unknown Error")

    console.error(
      // eslint-disable-next-line no-underscore-dangle
      `[ERROR] failed nextApiStoreRouterOpenapiDocument: path[${options.__dirname}] method:[${options.method}]`,
      err.message,
    )
    throw error
  }
})

// file: /src/app/api/users/[userId]/route.ts
import { routerSingleton } from "ApiRouter"

export const GET = routerSingleton.apiRouter(
  async ({ request }) => {
    console.log("requested", request.params.userId)
    return Promise.resolve({
      id: request.params.userId,
      name: "test user",
    })
  },
  {
    __dirname,
    method: "get",
    validation: {
      params: {
        userId: z.number().int().positive(),
      },
      response: z.object({
        id: z.number().int().positive(),
        name: z.string(),
      }),
    },
  },
)
Rendering open api with NextJS
// src/app/openapi/react-swagger.tsx
import "swagger-ui-react/swagger-ui.css"

import SwaggerUI from "swagger-ui-react"

type Props = {
  spec: Record<string, any>
}

function ReactSwagger({ spec }: Readonly<Props>) {
  return <SwaggerUI spec={spec} />
}

export default ReactSwagger

// src/app/openapi/page.tsx
import ReactSwagger from "./react-swagger"

import { nextApiCreateNextApiSwaggerSpec } from "@nystudio/nextapi-openapi"

export default async function IndexPage() {
  const spec = nextApiCreateNextApiSwaggerSpec({
    openapi: "3.0.0",
    info: {
      title: "Hello API",
      version: "1.0",
    },
  })

  return (
    <section className="container">
      <ReactSwagger spec={spec} />
    </section>
  )
}