J
J
Jedi2018-10-29 10:16:24
JavaScript
Jedi, 2018-10-29 10:16:24

How is it convenient to implement routing with a large list of routes on Koa?

Good morning!
I want to set up routing on Koa like this...

-routes
--users.js
--clients.js
--cars.js

You may have seen a similar structure if you have ever created a project through WebStorm on Express.js.
On Koa, I use Koa-router for routing .
How to implement a convenient structure for routing? One that I know I have described above. If you know the structures better, then please describe it, I will be grateful).
1) How to competently implement a convenient routing ecosystem?
2) How to implement it competently in terms of code?
I would be glad to see examples, if of course they exist.
Thanks a lot!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Kucherov, 2018-10-29
@PHPjedi

I would suggest putting the list of routes in one file altogether. After all, in essence, routing is just linking handlers to a specific URL (Sometimes with a middleware binding in the middle).
Next, put this file in the same directory with the entry point to the application and import the implementations of the handlers from the modules that are needed into it.
This will completely separate the implementation from the paths. And it will also allow you not to get confused in a huge number of paths and groups, because they will be in the same place.

// routes.js
import users from './users';
import posts from './posts';

router
  .get('/', app.homeHandler)
  .get('/posts', posts.listHandler)
  .post('/users', users.createHandler)
  .put('/users/:id',  users.changeHandler)
  .del('/users/:id', users.deleteHandler)
  .all('/users/:id', users.allHandler);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question