Last active
September 23, 2021 13:49
-
-
Save dernster/f1cfe82da2cf4c73c9cc5ee4336956cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************************* Types **************************************/ | |
export interface RouteType<ParamsType, NestedRoutesType> { | |
path: string; | |
build(params: ParamsType): string; | |
nestedRoutes: NestedRoutesType; | |
} | |
class Route<NestedRoutesType, ParamsType = void> | |
implements RouteType<ParamsType, NestedRoutesType> { | |
path: string; | |
private _build?(params: ParamsType): string; | |
nestedRoutes: NestedRoutesType; | |
constructor({ | |
path, | |
build, | |
nestedRoutes, | |
}: { | |
path: string; | |
build?: (params: ParamsType) => string; | |
nestedRoutes: NestedRoutesType; | |
}) { | |
this.path = path; | |
this._build = build; | |
this.nestedRoutes = nestedRoutes; | |
} | |
build = (params: ParamsType) => { | |
const _build = this._build ?? (() => this.path); | |
return _build(params); | |
}; | |
} | |
/************************************* Routes **************************************/ | |
const authRoutes = { | |
signIn: new Route({ path: '/sign-in', nestedRoutes: {} }), | |
signUp: new Route({ path: '/sign-up', nestedRoutes: {} }), | |
}; | |
const homeRoutes = { | |
dashboard: new Route({ | |
path: '/dashboard', | |
nestedRoutes: { | |
analytics: new Route({ | |
nestedRoutes: {}, | |
path: '/analytics/:chartId', | |
build: ({ | |
timePeriod, | |
chartId, | |
}: { | |
timePeriod: 'month' | 'day'; | |
chartId: string; | |
}) => `/analytics/${chartId}?period=${timePeriod}`, | |
}), | |
}, | |
}), | |
}; | |
const routes = { | |
auth: authRoutes, | |
home: homeRoutes, | |
}; | |
/************************************* Usage **************************************/ | |
routes.auth.signIn.build(); | |
routes.auth.signIn.path; | |
routes.home.dashboard.build(); | |
routes.home.dashboard.nestedRoutes.analytics.build({ | |
timePeriod: 'day', | |
chartId: 'id', | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment