koajs / router

Router middleware for Koa. Maintained by @forwardemail and @ladjs.
MIT License
849 stars 174 forks source link

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

Open Gabrirf opened 11 months ago

Gabrirf commented 11 months ago

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