Skip to content

Instantly share code, notes, and snippets.

@lkostrowski
Created May 5, 2020 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lkostrowski/3e5fe03c091d4e2829a4929f8ea76062 to your computer and use it in GitHub Desktop.
Save lkostrowski/3e5fe03c091d4e2829a4929f8ea76062 to your computer and use it in GitHub Desktop.
Route Object Pattern
/**
* Create a class/service, possibly don't export it so it's not confused with it's instance
*/
class SettingsRoute {
/**
* Expose public routes
* Can be also as getter functions - possible even better!
*/
public MAIN = `${this.baseUrl}settings`;
public SECURITY = `${this.baseUrl}settings/security`;
public NOTIFICATIONS = `${this.baseUrl}settings/notifications`;
/**
* Store some internal params so rest of app doesn't have to bother
*/
private passwordTokenParam = "token";
/**
* Provide base url prefix, so module can be mounted deeper in URL.
*/
constructor(private baseUrl = "/") {}
/**
* Don't let other parts of app decide where user goes by default.
* This is Settings Domain responsibility.
*/
getDefaultRoute(): string {
return this.NOTIFICATIONS;
}
/**
* Method like this can be used in inner navigation of settings panel etc.
*/
getAllRoutesSections(): string[] {
return [this.SECURITY, this.NOTIFICATIONS];
}
/**
* Add some function resolving some more complex url with params.
* Thanks to this there is only one place that handles this route both ways
*/
getPasswordChangeLinkWithToken(token: string): string {
return `${this.SECURITY}?${this.passwordTokenParam}=${token}`;
}
/**
* Opposite way to resolving, it should expose functions that parse some params
*/
getTokenFromPasswordChangeUrl(url: string): string {
const params = new URLSearchParams(url);
return params.get(this.passwordTokenParam);
}
}
/**
* Expose builder to encapsulate constructing logic
*/
export const SettingsRouteBuilder = {
build(options?: { baseUrl?: string }): SettingsRoute {
return new SettingsRoute(options?.baseUrl);
}
};
/**
* Export created route object instance
*/
export const settingsRoute = new SettingsRoute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment