router icon indicating copy to clipboard operation
router copied to clipboard

[fix] router.use method doesn't work with RegExp

Open Gabrirf opened this issue 1 year ago • 0 comments

Describe the bug

Node.js version: 18.17.1

@koa/router: 12.0.0

Typescript target: ES2020

OS version: Windows 10 Enterprise

Description: router.use method doesn't work with RegExp

Actual behavior

I'm trying to set a middleware for just some routes in a path by using RegExp. It appears the error

([^/]*)`: `middleware` must be a function, not `object

I think that there is a bug with selecting the RegExp type because it does not match against the defined method in the Router class and it uses the first one. Should be using the second definition:

declare class Router<StateT = Koa.DefaultState, ContextT = Koa.DefaultContext> {
    use(...middleware: Array<Router.Middleware<StateT, ContextT>>): Router<StateT, ContextT>;

    use(
        path: string | string[] | RegExp,
        ...middleware: Array<Router.Middleware<StateT, ContextT>>
    ): Router<StateT, ContextT>;
}

Expected behavior

Should work the same as using:

router.use(['/a1', '/a2'], middleware);

Code to reproduce

import Router from '@koa/router';
const router= new Router();

const regexp = new RegExp('/^a.*/');
router.use(regexp, middleware);

router.post('/a1', func1);
router.post('/a2', func2);
router.post('/b1', func3);

export default router;

Checklist

  • [ X] I have searched through GitHub issues for similar issues.
  • [ X] I have completely read through the README and documentation.
  • [ X] I have tested my code with the latest version of Node.js and this package and confirmed it is still not working.

Gabrirf avatar Sep 14 '23 11:09 Gabrirf