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

next-api-decorators

v2.0.2

Published

Collection of decorators to create typed Next.js API routes, with easy request validation and transformation.

Downloads

14,204

Readme


View docs


Basic usage

// pages/api/user.ts
class User {
  // GET /api/user
  @Get()
  async fetchUser(@Query('id') id: string) {
    const user = await DB.findUserById(id);

    if (!user) {
      throw new NotFoundException('User not found.');
    }

    return user;
  }

  // POST /api/user
  @Post()
  @HttpCode(201)
  async createUser(@Body(ValidationPipe) body: CreateUserDto) {
    return await DB.createUser(body.email);
  }
}

export default createHandler(User);

💡 Read more about validation here

export default async (req: NextApiRequest, res: NextApiResponse) => {
  if (req.method === 'GET') {
    const user = await DB.findUserById(req.query.id);
    if (!user) {
      return res.status(404).json({
        statusCode: 404,
        message: 'User not found'
      })
    }

    return res.json(user);
  } else if (req.method === 'POST') {
    // Very primitive e-mail address validation.
    if (!req.body.email || (req.body.email && !req.body.email.includes('@'))) {
      return res.status(400).json({
        statusCode: 400,
        message: 'Invalid e-mail address.'
      })
    }

    const user = await DB.createUser(req.body.email);
    return res.status(201).json(user);
  }

  res.status(404).json({
    statusCode: 404,
    message: 'Not Found'
  });
}

Motivation

Building serverless functions declaratively with classes and decorators makes dealing with Next.js API routes easier and brings order and sanity to your /pages/api codebase.

The structure is heavily inspired by NestJS, which is an amazing framework for a lot of use cases. On the other hand, a separate NestJS repo for your backend can also bring unneeded overhead and complexity to projects with a smaller set of backend requirements. Combining the structure of NestJS, with the ease of use of Next.js, brings the best of both worlds for the right use case.

If you are not familiar with Next.js or NestJS and want some more information (or need to be convinced), check out the article Awesome Next.js API Routes with next-api-decorators by @tn12787

Installation

Visit https://next-api-decorators.vercel.app/docs/#installation to get started.

Documentation

Refer to our docs for usage topics:

Validation

Route matching

Using middlewares

Custom middlewares

Pipes

Exceptions

Available decorators

Class decorators

| | Description | | ----------------------------------------- | -------------------------------------------------------------- | | @SetHeader(name: string, value: string) | Sets a header name/value into all routes defined in the class. | | @UseMiddleware(...middlewares: Middleware[]) | Registers one or multiple middlewares for all the routes defined in the class. |

Method decorators

| | Description | | ----------------------------------------- | ------------------------------------------------- | | @Get(path?: string) | Marks the method as GET handler. | | @Post(path?: string) | Marks the method as POST handler. | | @Put(path?: string) | Marks the method as PUT handler. | | @Delete(path?: string) | Marks the method as DELETE handler. | | @Patch(path?: string) | Marks the method as PATCH handler. | | @SetHeader(name: string, value: string) | Sets a header name/value into the route response. | | @HttpCode(code: number) | Sets the http code in the route response. | | @UseMiddleware(...middlewares: Middleware[]) | Registers one or multiple middlewares for the handler. |

Parameter decorators

| | Description | | ----------------------- | ------------------------------------------- | | @Req() | Gets the request object. | | @Res()* | Gets the response object. | | @Body() | Gets the request body. | | @Query(key: string) | Gets a query string parameter value by key. | | @Header(name: string) | Gets a header value by name. | | @Param(key: string) | Gets a route parameter value by key. |

* Note that when you inject @Res() in a method handler you become responsible for managing the response. When doing so, you must issue some kind of response by making a call on the response object (e.g., res.json(...) or res.send(...)), or the HTTP server will hang.