Skip to content

Commit

Permalink
Merge pull request topcoder-platform#5427 from topcoder-platform/rout…
Browse files Browse the repository at this point in the history
…e-redirects

Route redirects
  • Loading branch information
luizrrodrigues committed Mar 11, 2021
2 parents 5e4a4ef + e92c162 commit 25d33a5
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .circleci/config.yml
Expand Up @@ -283,7 +283,7 @@ workflows:
filters:
branches:
only:
- gigwork-updates
- route-redirects
# This is alternate dev env for parallel testing
- "build-qa":
context : org-global
Expand Down
31 changes: 29 additions & 2 deletions src/shared/components/Contentful/Route.jsx
Expand Up @@ -10,9 +10,10 @@ import LoadingIndicator from 'components/LoadingIndicator';
import MetaTags from 'components/MetaTags';
import PT from 'prop-types';
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import { Route, Switch, Redirect } from 'react-router-dom';
import Viewport from 'components/Contentful/Viewport';
import PasswordScreen from 'components/Contentful/PasswordScreen';
import { isomorphy } from 'topcoder-react-utils';

// Concatenates a base and segment and handles optional trailing slashes
const buildUrl = (base, segment) => `${_.trimEnd(base, '/')}/${_.trim(segment, '/')}`;
Expand Down Expand Up @@ -117,6 +118,29 @@ ChildRoutesLoader.propTypes = {
url: PT.string.isRequired,
};

function RedirectWithStatus({ from, to, status }) {
return (
<Route
render={({ staticContext }) => {
if (to[0] !== '/' && isomorphy.isClientSide()) {
window.location.href = to;
return null;
}
// there is no `staticContext` on the client, so
// we need to guard against that here
if (staticContext) staticContext.status = status;
return <Redirect from={from} to={to} />;
}}
/>
);
}

RedirectWithStatus.propTypes = {
from: PT.string.isRequired,
to: PT.string.isRequired,
status: PT.number.isRequired,
};

export default function ContentfulRoute(props) {
const {
baseUrl,
Expand Down Expand Up @@ -145,7 +169,10 @@ export default function ContentfulRoute(props) {
render={(data) => {
const { fields } = Object.values(data.entries.items)[0];
const url = path || buildUrl(baseUrl, fields.url);
return (
const redirectToUrl = _.trim(fields.redirectToUrl);
return redirectToUrl ? (
<RedirectWithStatus status={301} from={url} to={redirectToUrl} />
) : (
<Route
/* This route prevents fetching data about child routes and their
* rendering, if they already known to not match. */
Expand Down
1 change: 1 addition & 0 deletions src/shared/routes/index.jsx
Expand Up @@ -97,6 +97,7 @@ function Routes({ communityId }) {
path="/community/(competitive-programming|data-science|design|development|qa)/how-to-compete"
/>
<Redirect
exact
from="/community/gigs"
to="/gigs"
/>
Expand Down

0 comments on commit 25d33a5

Please sign in to comment.