Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/how_tos/migrate-frontend-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,7 @@ Other configuration is now optional, and many values have been given sensible de
URL Config changes
------------------

Note that the .env files and env.config.js files also include a number of URLs for various micro-frontends and services. These URLs should now be expressed as part of the `apps` config as route roles, or as `externalRoutes`, and resolved in code via `resolveRouteByRole()`. It substitutes route params, drops a trailing splat, and reports whether the result is a path in this site or an external URL, so a link can stay in the client when it is. `getLinkProps()` turns any URL into the props for a component that accepts `as`, a react-router `Link` for a path in this site and a plain anchor otherwise.
Note that the .env files and env.config.js files also include a number of URLs for various micro-frontends and services. These URLs should now be expressed as part of the `apps` config as route roles, or as `externalRoutes`, and resolved in code via `resolveRouteByRole()`. It substitutes route params (in an external URL too, wherever a `:name` token matches a given param), drops a trailing splat, and reports whether the result is a path in this site or an external URL, so a link can stay in the client when it is. `getLinkProps()` turns any URL into the props for a component that accepts `as`, a react-router `Link` for a path in this site and a plain anchor otherwise. When both an app and `externalRoutes` provide a role, the external route wins, so a site can point a role an app declares somewhere else.

```js
// Creating a route role with for 'example' in an App
Expand Down
38 changes: 34 additions & 4 deletions runtime/routing/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,21 @@ describe('getUrlByRouteRole', () => {
expect(getUrlByRouteRole('org.openedx.frontend.role.login')).toBe('https://auth.example.com/login');
});

it('prefers an external route over an app route for the same role', () => {
mockGetSiteConfig.mockReturnValue({
apps: [{
appId: 'authn',
routes: [{ path: '/authn/login', handle: { roles: ['org.openedx.frontend.role.login'] } }],
}],
externalRoutes: [{
role: 'org.openedx.frontend.role.login',
url: 'https://auth.example.com/login',
}],
} as any);

expect(getUrlByRouteRole('org.openedx.frontend.role.login')).toBe('https://auth.example.com/login');
});

it('returns null when no matching role is found', () => {
mockGetSiteConfig.mockReturnValue({
apps: [],
Expand Down Expand Up @@ -89,10 +104,10 @@ describe('resolveRouteByRole', () => {
{ path: '/*', handle: { roles: ['catch-all'] } },
],
}],
externalRoutes: [{
role: 'profile',
url: 'https://apps.example.com/profile/',
}],
externalRoutes: [
{ role: 'profile', url: 'https://apps.example.com/profile/' },
{ role: 'dates', url: 'http://lms.example.com:8000/courses/:courseId/dates?tab=:tab' },
],
} as any);
});

Expand Down Expand Up @@ -125,6 +140,21 @@ describe('resolveRouteByRole', () => {
.toEqual({ url: 'https://apps.example.com/profile/', isInternal: false });
});

it('fills the params of an external URL, URL-encoded', () => {
expect(resolveRouteByRole('dates', { courseId: 'course-v1:edX+DemoX+Demo_Course', tab: 'a b' }))
.toEqual({
url: 'http://lms.example.com:8000/courses/course-v1%3AedX%2BDemoX%2BDemo_Course/dates?tab=a%20b',
isInternal: false,
});
});

it('leaves the tokens of an external URL that have no param alone', () => {
expect(resolveRouteByRole('dates', { courseId: 'c1' }))
.toEqual({ url: 'http://lms.example.com:8000/courses/c1/dates?tab=:tab', isInternal: false });
expect(resolveRouteByRole('dates', { courseId: 'c1', tab: undefined } as any))
.toEqual({ url: 'http://lms.example.com:8000/courses/c1/dates?tab=:tab', isInternal: false });
});

it('returns null when nothing provides the role', () => {
expect(resolveRouteByRole('nonexistent')).toBeNull();
});
Expand Down
43 changes: 30 additions & 13 deletions runtime/routing/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,24 @@ function findRoleInRoutes(routes: RouteObject[], role: string, prefix = ''): str
return null;
}

/**
* The URL the site links to for `role`, if any. The site's `externalRoutes` take precedence
* over the routes of installed apps, so a site can send a role an app declares elsewhere.
*
* @param {string} role
* @returns {string|null}
*/
export function getUrlByRouteRole(role: string) {
const { apps, externalRoutes } = getSiteConfig();

if (externalRoutes) {
for (const externalRoute of externalRoutes) {
if (externalRoute.role === role) {
return externalRoute.url;
}
}
}

if (apps) {
for (const app of apps) {
if (Array.isArray(app.routes)) {
Expand All @@ -38,17 +53,18 @@ export function getUrlByRouteRole(role: string) {
}
}

if (externalRoutes) {
for (const externalRoute of externalRoutes) {
if (externalRoute.role === role) {
return externalRoute.url;
}
}
}

return null;
}

/* Fills the `:name` tokens of an external URL from `params`, URL-encoded. */
function fillExternalUrlParams(url: string, params: Record<string, string>) {
return url.replace(/:([A-Za-z_][\w-]*)/g, (token, name) => (
Object.prototype.hasOwnProperty.call(params, name) && params[name] != null
? encodeURIComponent(params[name])
: token
));
}

export function isRoleRouteObject(match: RouteObject): match is RoleRouteObject {
return match.handle !== undefined && 'roles' in match.handle;
}
Expand All @@ -72,10 +88,11 @@ export interface ResolvedRoute {
}

/**
* Resolves the route the site provides for `role`, if any, ready to link to: the path of an
* installed app's route, or the URL of an external route, as `getUrlByRouteRole` finds it. An app
* route's path has its params filled from `params` and a trailing splat dropped, as react-router's
* `generatePath` does, so a missing required param throws; an external URL is returned as
* Resolves the route the site provides for `role`, if any, ready to link to: the URL of an
* external route, or the path of an installed app's route, as `getUrlByRouteRole` finds it. A
* path in this site has its params filled from `params` and a trailing splat dropped, as
* react-router's `generatePath` does, so a missing required param throws; an external URL has the
* `:name` tokens that `params` provides filled in, URL-encoded, and is otherwise returned as
* configured. `isInternal` tells the two apart.
*
* ```
Expand All @@ -96,7 +113,7 @@ export function resolveRouteByRole(role: string, params: Record<string, string>
return null;
}
const isInternal = isInternalUrl(path);
return { url: isInternal ? generatePath(path, params) : path, isInternal };
return { url: isInternal ? generatePath(path, params) : fillExternalUrlParams(path, params), isInternal };
}

export interface LinkProps {
Expand Down
5 changes: 5 additions & 0 deletions types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ import { AuthService } from './runtime/auth/types';

// Apps

/**
* Where the site links to for a route role. Takes precedence over an installed app's route for
* the same role.
*/
export interface ExternalRoute {
role: string;
/** May contain `:name` tokens, filled from the params a link is resolved with. */
url: string;
}

Expand Down
Loading