UNPKG

next-connect

Version:

The method routing and middleware layer for Next.js (and many others)

76 lines (75 loc) 2.52 kB
import { Router } from "./router.js"; export class EdgeRouter { constructor() { this.router = new Router(); this.all = this.add.bind(this, ""); this.get = this.add.bind(this, "GET"); this.head = this.add.bind(this, "HEAD"); this.post = this.add.bind(this, "POST"); this.put = this.add.bind(this, "PUT"); this.patch = this.add.bind(this, "PATCH"); this.delete = this.add.bind(this, "DELETE"); } add(method, route, ...fns) { this.router.add(method, route, ...fns); return this; } use(base, ...fns) { if (typeof base === "function" || base instanceof EdgeRouter) { fns.unshift(base); base = "/"; } this.router.use(base, ...fns.map((fn) => (fn instanceof EdgeRouter ? fn.router : fn))); return this; } prepareRequest(req, ctx, findResult) { req.params = { ...findResult.params, ...req.params, // original params will take precedence }; } clone() { const r = new EdgeRouter(); r.router = this.router.clone(); return r; } async run(req, ctx) { const result = this.router.find(req.method, getPathname(req)); if (!result.fns.length) return; this.prepareRequest(req, ctx, result); return Router.exec(result.fns, req, ctx); } handler(options = {}) { const onNoMatch = options.onNoMatch || onnomatch; const onError = options.onError || onerror; return async (req, ctx) => { const result = this.router.find(req.method, getPathname(req)); this.prepareRequest(req, ctx, result); try { if (result.fns.length === 0 || result.middleOnly) { return await onNoMatch(req, ctx); } else { return await Router.exec(result.fns, req, ctx); } } catch (err) { return onError(err, req, ctx); } }; } } function onnomatch(req) { return new Response(req.method !== "HEAD" ? `Route ${req.method} ${req.url} not found` : null, { status: 404 }); } function onerror(err) { console.error(err); return new Response("Internal Server Error", { status: 500 }); } export function getPathname(req) { return (req.nextUrl || new URL(req.url)).pathname; } export function createEdgeRouter() { return new EdgeRouter(); }