kriasoft / universal-router

A simple middleware-style router for isomorphic JavaScript web apps
https://www.kriasoft.com/universal-router/
MIT License
1.7k stars 105 forks source link

Simple Change: Make resolveRoute a class member of UniversalRouter instead of privately scoped #205

Open joezappie opened 2 years ago

joezappie commented 2 years ago

I'm submitting a ...

Feature request

Would there be any backwards compatibility issues with moving the resolveRoute function to be inside the UniversalRouter class? The reason for this is when extending UniversalRouter, you cannot override the resolveRoute function as its a privately scoped function in the UniversalRouter.js file, outside of the UniversalRouter class.

Currently I have my resolveRouter passed in as a parameter, but I have a custom class for my router to add in functionality like history API. Being able to override resolveRouter inside that class would be a cleaner interface, keeping like logic together. I don't see any conflicts with this change and would improve class support. Is there a good reason for this to stay as a private function?

Proposed Change

class UniversalRouter {
    constructor(routes, options) {
         ...
    }

    resolve(pathnameOrContext) {
        ....
        const resolve = this.options.resolveRoute || this.resolveRoute;
        ...
    }

    resolveRoute(context, params) {
        if (typeof context.route.action === 'function') {
            return context.route.action(context, params);
        }
        return undefined;
    }
}

Then custom router classes can override it or it can still be passed in as an option.

class MyRouter extends UniversalRouter {
    resolveRoute(context, params) {
        // custom logic
    }
}
frenzzy commented 2 years ago

You can override resolveRoute in your custom class like this:

class YourRouter extends UniversalRouter {
  constructor(routes, options) {
    super(routes, { ...options, resolveRoute: this.resolveRoute })
  }
  resolveRoute(context, params) {
    // custom logic
  }
}

But could you tell us a little about why you need to extend the UniversalRouter class, i.e. what functionality are you missing?