restyped-express-async icon indicating copy to clipboard operation
restyped-express-async copied to clipboard

Nesting

Open Gregoor opened this issue 7 years ago • 3 comments

Cool project, thanks a lot for doing this! I'm considering using this in http://voice.mozilla.org (https://github.com/mozilla/voice-web).

Currently we nest our routers e.g.

app.use('/api', api.getRouter());

api.getRouter = () =>{
  const router = Router();
  router.get('/clips', this.serveClips);
  return router;
}

From reading the docs, it looks like this wouldn't be possible as the subrouters don't specify the full route. If my assessment is correct, would you be interested in having this? Then I'll work on a PR for it.

Gregoor avatar Feb 12 '18 15:02 Gregoor

I'm not sure if this is exactly what you're looking for, but it's definitely possible to nest a RESTyped router. I'm doing it in a few projects like so:

import RestypedRouter from 'restyped-express-async'
const apiRouter = express.Router()
app.use('/api', apiRouter)
const api = RestypedRouter<API>(apiRouter)

rawrmaan avatar Feb 23 '18 06:02 rawrmaan

That's not quite what I had in mind. I'd like to nest a RESTyped router in a RESTyped router, like so:

user.getRouter = () =>{
  const router = Router();
  router.get('/:id', this.serveUser);
  return RestypedRouter<UserAPI>(router);
}

clip.getRouter = () =>{
  const router = Router();
  router.get('/:id', this.serveClip);
  return RestypedRouter<ClipAPI>(router);
}

const apiRouter = Router();
const api = RestypedRouter<API>(apiRouter)
api.use('/users', user.getRouter());
api.use('/clips', clip.getRouter());

Gregoor avatar Feb 26 '18 10:02 Gregoor

If I'm not mistaken, you've got the router creation code a bit backwards in your getRouter functions, although you get it right at the end of the snippet. I believe the following should work:

user.getRouter = () =>{
  const router = Router();
  const userApi = RestypedRouter<UserAPI>(router);
  userApi.get('/:id', this.serveUser);
  return router;
}

Does this solve your use case?

rawrmaan avatar Apr 06 '18 02:04 rawrmaan