From b42c5370643c8b8b43ea95463bfb26bd846a3483 Mon Sep 17 00:00:00 2001 From: Jim Isaacs Date: Sun, 10 Apr 2022 15:50:31 +0000 Subject: [PATCH] fix(#161): use() accepts array --- src/index.d.ts | 3 +++ src/index.js | 3 ++- test/index.test.js | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/index.d.ts b/src/index.d.ts index cd75be6..a3664a8 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -33,6 +33,9 @@ declare module "next-connect" { interface NextConnect { (req: Req, res: Res): Promise; + use( + handlers: Middleware[] + ): this; use( ...handlers: Middleware[] ): this; diff --git a/src/index.js b/src/index.js index bf7a7d3..29bdaed 100644 --- a/src/index.js +++ b/src/index.js @@ -35,7 +35,8 @@ export default function factory({ return nc; } nc.use = function use(base, ...fns) { - if (typeof base === "function") return this.use("/", base, ...fns); + if (Array.isArray(base)) return this.use("/", ...base); + if (Array.isArray(base) || typeof base === "function") return this.use("/", base, ...fns); 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 44632c7..448f6e2 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -294,6 +294,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) => {