Skip to content

Commit

Permalink
fix(#161): use() accepts array
Browse files Browse the repository at this point in the history
  • Loading branch information
jimisaacs authored Oct 29, 2021
1 parent 14aa547 commit b221569
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ declare module "next-connect" {
...handlers: Middleware<Req & ReqExt, Res & ResExt>[]
): this;
use<ReqExt = {}, ResExt = {}>(
pattern: string | RegExp,
pattern: string | RegExp | readonly (string | RegExp)[],
...handlers: Middleware<Req & ReqExt, Res & ResExt>[]
): this;

Expand Down
6 changes: 5 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
18 changes: 18 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down

0 comments on commit b221569

Please sign in to comment.