felixblaschke / shelf_plus

MIT License
73 stars 14 forks source link

how to create a subroute in another module, or how to create subroute using mount, or how to merge multiple handler - all with passing extra parameter like database and some extra context infos #35

Closed leefordjudes closed 9 months ago

leefordjudes commented 9 months ago

Hi, I am straight away using Shelf Plus with a database, (without using shelf) here I have many modules, so I need to divide a single handler file into multiple handler files with subroutes for each module, I searched in your examples, got nothing,

can you give an example for creating sub route for each module and splite handler and merge handler, or how to use mount or is there any way,

felixblaschke commented 9 months ago

Hey. Shelf Plus basically is just a fancy abstraction on package shelf_router and just comes with some opinionated request handler. I understood you want to modularize your api. Analogue to shelf_router you can do this with the .mount() method to combine multiple routers.

I let Gemini generate example code:

void main() async {
  var app = Router().plus;

  // Mount sub-routers with middleware for specific modules if needed
  app.mount('/users/', userHandler());
  app.mount('/products/', productHandler());

  // Global middleware (e.g., logging, CORS)
  app.use(cors()); 
  app.use(requestLogger());

  var server = await shelf_io.serve(app, 'localhost', 8080); // you can also use shelfRun here
  print('Server running on http://${server.address.host}:${server.port}');
}

Router userHandler() {
  var router = Router().plus;

  router.get('/', () => 'List of users');
  router.get('/<userId>', (Request request, String userId) => 'User details for $userId');
  // ... more user-specific routes

  return router;
}

Router productHandler() {
  var router = Router().plus;

  router.get('/', () => 'List of products');
  router.post('/', () => 'Create a new product'); 
  // ... more product-specific routes

  return router;
}
leefordjudes commented 9 months ago

Thankyou very much.