next-controllers
TypeScript icon, indicating that this package has built-in type declarations

0.1.17 • Public • Published

Next-Controllers

A library for create api routes for NextJS.

Installation

Install with npm

npm i next-controllers

Or yarn

yarn add next-controllers

Setup

  1. Enable decorators in your tsconfig.ts:

    {
      "experimentalDecorators": true,
      "emitDecoratorMetadata": true
    }
  2. Add or modify a .babelrc file with the following content:

    {
      "presets": ["next/babel"],
      "plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }], "@babel/plugin-proposal-class-properties"]
    }
  3. Install the babel dependencies

    npm i -D @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators
    

Usage

Create a file under pages/api/ with the pattern: [[...params]] to allow catch all the request.

Define the controller on the route.

// pages/api/[...hello].ts

import { Get, NextApiContext, withController } from 'next-controllers';

class HelloController {
  @Get()
  sayHello() {
    return 'Hello World!';
  }

  @Get('/:name')
  sayHelloTo(context: NextApiContext) {
    return `Hello ${context.request.params.name}!`;
  }
}

export default withController(HelloController);

Request results:

curl http://localhost:3000/api
> Hello World!
curl http://localhost:3000/api/Alexandra
> Hello Alexandra!

Package Sidebar

Install

npm i next-controllers

Weekly Downloads

1

Version

0.1.17

License

MIT

Unpacked Size

130 kB

Total Files

72

Last publish

Collaborators

  • neociber94