koajs / joi-router

Configurable, input and output validated routing for koa
MIT License
450 stars 96 forks source link

Prefix not work when pass router to another router using r.route #126

Closed Roma-Kyrnis closed 3 years ago

Roma-Kyrnis commented 3 years ago

I pass router to router using r.use and prefix work fine. But when I try to pass using r.route prefix not work, I think it is because router delegate work to @koa/router.

Can you handler this problem that I can you r.route with prefix and add documentation: "Passing through routers and be able use prefix"

Roma-Kyrnis commented 3 years ago
  1. Work with prefix:
    
    const Router = require('koa-joi-router');

const events = Router(); events.prefix('/events'); events.get('/', { validate: validator.getAll }, events.getAll);

const apiV1 = Router(); apiV1.prefix('/api/v1'); apiV1.use(events); // DIFFERENCE

module.exports = apiV1;


2. Not work with prefix:
``` javascript
const Router = require('koa-joi-router');

const events = Router();
events.prefix('/events');
events.get('/', { validate: validator.getAll }, events.getAll);

const apiV1 = Router();
apiV1.prefix('/api/v1');
apiV1.route(events.routes); // DIFFERENCE

module.exports = apiV1;

Use router with server:

const Koa = require('koa');

const apiV1 = require('./apiV1');

const app = new Koa();

app.use(apiV1.middleware());
3imed-jaberi commented 3 years ago

You can use the Prefix path as constant like this;

const EVENTS_PREFIX_ROUTE = '/events'

Then use it like that and every thing work fine.

const Router = require('koa-joi-router');

const events = Router();
events.prefix(EVENTS_PREFIX_ROUTE);
events.get('/', { validate: validator.getAll }, events.getAll);

const apiV1 = Router();
apiV1.prefix('/api/v1');
apiV1.route(events.routes.map(route => ({ ...route, path: (EVENTS_PREFIX_ROUTE + route.path).slice(0, -1) }))); // WORK

module.exports = apiV1;
Roma-Kyrnis commented 3 years ago

I use constants. But, I think, this code is so long for one line

3imed-jaberi commented 3 years ago

@Roman-Kirnos, you can create a util or helper file then add this fucntion to it.

// helper/util file
function routesWrap (router, PREFIX) {
  return router.routes.map(route => ({ 
    ...route,
    path: (PREFIX + route.path).slice(0, -1) 
  }))
}

Now, it's shorter.

const Router = require('koa-joi-router');

const events = Router();
events.prefix(EVENTS_PREFIX_ROUTE);
events.get('/', { validate: validator.getAll }, events.getAll);

const apiV1 = Router();
apiV1.prefix('/api/v1');
apiV1.route(routesWrap(events, EVENTS_PREFIX_ROUTE)); // WORK

module.exports = apiV1;
Roma-Kyrnis commented 3 years ago

Thank you! I appreciate your help very much)