moleculerjs / moleculer-web

:earth_africa: Official API Gateway service for Moleculer framework
http://moleculer.services/docs/moleculer-web.html
MIT License
292 stars 118 forks source link

Improve routes priorization #335

Open srosset81 opened 9 months ago

srosset81 commented 9 months ago

When routes are added via the addRoute action, it's difficult to control the priority of the routes added. The toBottom parameter doesn't work well because if other services call addRoute later, their routes will be added below.

This is a problem especially when there are catch-all routes which must imperatively be handled at the very end.

A solution could be to set a priority option (as a number) to routes. Higher-priority routes would bypass lower-priority routes in the optimizeRouteOrder method.

What do you think ?

For now I've found a temporary solution by adding a catchAll option to routes and overwriting the optimizeRouteOrder method to ensure these catch-all routes are handled last:

  methods: {
    optimizeRouteOrder() {
      // Overwrite optimization method to put catchAll routes at the end
      this.routes.sort((a, b) => (a.opts.catchAll ? 1 : -1));
      this.aliases.sort((a, b) => (a.route.opts.catchAll ? 1 : -1));
    },
  }
icebob commented 9 months ago

Good idea, a priority route setting can be good. Could you work on a draft PR?