🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

next-compose-router

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

next-compose-router

create koa-router like next.js handler

latest
Source
npmnpm
Version
1.0.4
Version published
Weekly downloads
3
-70%
Maintainers
1
Weekly downloads
 
Created
Source

next-compose-router

Create koa-router like handler for next.js.

Installation

$ npm install next-compose-router

Why not middleware

Sometimes not all api need some validation operates, and as my Koa develop experiences, I prefer defining some apis' preprocessing separately and flexibly. So I write this toolkit to handle this

Maintainers

  • @littlebadbad

API

router

Create a next handler composed with multi middlewares

import {router} from "next-compose-router"

// usage
export default router(checkAuth, checkParams, (req, res) => {
    // write handler here
    res.send("success")
})

// others
export const FORBIDDEN = {message: "forbidden", status: 403}

export const BAD_REQUEST: IError = {message: "bad request", status: 400}

async function checkAuth(req, res, next) {
    const token = req.headers.authorization
    if (valid(token)) { // valid token here
        await next()
    } else {
        throw FORBBIDEN
    }
}

async function checkParams(req, res, next) {
    const params = req.query
    if (valid(params)) { // valid params here
        await next()
    } else {
        throw BAD_REQUEST
    }
}

nextCompose

Used to define self error handler

import {nextCompose} from "next-compose-router"

// default
const router = nextCompose((req, res, err) => {
    throw err
})

const myRouter = nextCompose((req, res, {status, message}) => {
    res.statusCode = status || 500
    res.send({
        error: {
            status: status || 500,
            message: status ? message : "internal error"
        }
    })
})

License

MIT

Keywords

next

FAQs

Package last updated on 04 Apr 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts