From b2215696c85d0abafcebcdffe4a4f147bb4fb22a Mon Sep 17 00:00:00 2001 From: Jim Isaacs Date: Fri, 29 Oct 2021 02:00:15 +0000 Subject: [PATCH] fix(#161): use() accepts array --- src/index.d.ts | 2 +- src/index.js | 6 +++++- test/index.test.js | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/index.d.ts b/src/index.d.ts index 6cc4f47..0a68cd7 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -29,7 +29,7 @@ declare module "next-connect" { ...handlers: Middleware[] ): this; use( - pattern: string | RegExp, + pattern: string | RegExp | readonly (string | RegExp)[], ...handlers: Middleware[] ): this; diff --git a/src/index.js b/src/index.js index dd0a2c3..25087bc 100644 --- a/src/index.js +++ b/src/index.js @@ -26,7 +26,11 @@ export default function factory({ return nc; } nc.use = function use(base, ...fns) { - if (typeof base === "function") return this.use("/", base, ...fns); + if (typeof base === "function") return nc.use("/", base, ...fns); + if (Array.isArray(base)) { + for (const p of base) nc.use(p, ...fns); + return nc; + } if (typeof base === "string" && base !== "/") { let slashAdded = false; fns.unshift((req, _, next) => { diff --git a/test/index.test.js b/test/index.test.js index 32b0a61..331b449 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -226,6 +226,24 @@ describe("use()", () => { await request(app).get("/some/path").expect("no"); }); + it("match path by array of RegExp and base", async () => { + const handler = nc(); + handler.use([new RegExp("/this|/that"), '/the/other/'], (req, res, next) => { + req.ok = "ok"; + next(); + }); + handler.get((req, res) => { + res.end(req.ok || "no"); + }); + const app = createServer(handler); + await request(app).get("/this/that/these/those").expect("ok"); + await request(app).get("/this").expect("ok"); + await request(app).get("/that/this/these/those").expect("ok"); + await request(app).get("/that").expect("ok"); + await request(app).get("/some/path").expect("no"); + await request(app).get("/the/other/path").expect("ok"); + }); + it("mount subapp", () => { const handler2 = nc(); handler2.use((req, res, next) => {