ZijianHe / koa-router

Router middleware for koa.
MIT License
4.85k stars 407 forks source link

how to get route path #361

Closed willin closed 7 years ago

willin commented 7 years ago
const Koa = require('koa');
const router = require('koa-router')();
const logger = require('..');

const app = new Koa();

// test route
router.get('/name/:id', (ctx) => {
  console.log(ctx.route);
  ctx.body = ctx.params.id;
});

app.use(async(ctx,next)=>{
    // log start time
    const start = new Date();
    try {
      await next();
    } catch (err) {

    }

    // log end time
    const end = new Date();
    // i want to log like: route /name/:id 4ms
    console.log('route', ctx.route, end - start, 'ms');
   // ctx.route undefined
  };
});

app.use(router.routes())
  .use(router.allowedMethods());

app.listen(3000);
jbielick commented 7 years ago

When a route is matched, its path is available at ctx._matchedRoute and if named, the name is available at ctx._matchedRouteName

willin commented 7 years ago

@jbielick we are using koa-joi-router which is using a forked old version of koa-router, how can i get the ctx._matchedRoute with high performance?

koajs/joi-router/issues/53

jbielick commented 7 years ago

I don't contribute to joi-router and do not know it's API. Please consult that project and it's maintainers.

thanhlq commented 6 years ago

Hi!,

In the example above, is it possible for me to get the _matchedRoute before going to the user router middleware?

const Koa = require('koa');
const router = require('koa-router')();
const logger = require('..');

const app = new Koa();

// test route
router.get('/name/:id', (ctx) => {
  console.log(ctx.route);
  ctx.body = ctx.params.id;
});

app.use(async(ctx,next)=>{

   // I want to get _matchedRoute to apply some policies before going to the user router.   
   // i.e. ctx._matchedRoute
   //...

    try {
      await next();
    } catch (err) {
    }

});

app.use(router.routes())
  .use(router.allowedMethods());

app.listen(3000);
mirague commented 5 years ago

I wonder this too, is it possible to register an "empty" router to figure out the _matchedRoute before rendering the actual route handlers? @jbielick