1.0.8 • Published 3 years ago

@arisris/next-api-router v1.0.8

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

Next.js Api Router

A chainable router designed for Next.js api. inspired and regex based from itty-router

Features

  • Tiny (~8xx bytes compressed) with zero dependencies.
  • Strong typing with typescript also javascript with VSCode
  • Anything is async/await handler
  • Route params, with wildcards and optionals (e.g. /base/:collection/:id?)
  • Middleware support
  • By default error handler response is json
  • Support anything of HTTP methods
  • Chainable route declarations
  • No dependencies

Installation

npm i @arisris/next-api-router

Example Usage

// file: pages/api/[...any].ts
import NextApiRoute from "@arisris/next-api-router";

export default NextApiRoute({
  key: "all", // a rest params default to "any"
  timeout: 5000, // timeout in ms default to 10000ms
  //onError: (error, req, res) => res.status(500).send("Internal Server Error") // By default handled with json response
})
  .all("*", async () => true) // middleware should return true
  .get("/hello", async (_, res) => res.send("Hello World")) // simple
  .get(
    "/wait",
    async () => await new Promise((resolve) => setTimeout(resolve, 3000)), // wait for 3000ms
    async (_, res) => res.json({ msg: "Done..." })
  )
  .get("/error", async () => {
    throw new Error("OMG!");
  })
  .get("/timeout", async () => {
    // No response is considered timeout
  })
  .get("/user/:name?", async (req, res) => res.json({ params: req.params }))
  // not found
  .all("*", async (_, res) => res.status(404).send("Not Found"))
  .handle; // Final handler of NextApiHandler

Todo better documentation

--

Links

My Website itty-router

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago