Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Obey url rewrites in browser-side routing #463

Merged
merged 6 commits into from
Jan 10, 2019
Merged
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
10 changes: 8 additions & 2 deletions src/containers/tags/withTag.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from "react";
import PropTypes from "prop-types";
import { Query } from "react-apollo";
import { inject, observer } from "mobx-react";
import hoistNonReactStatic from "hoist-non-react-statics";
import tagQuery from "./tag.gql";

Expand All @@ -11,6 +12,8 @@ import tagQuery from "./tag.gql";
* @returns {React.Component} - Component with `tag` prop
*/
export default function withTag(Component) {
@inject("routingStore")
@observer
class WithTag extends React.Component {
static propTypes = {
/**
Expand All @@ -20,10 +23,13 @@ export default function withTag(Component) {
}

render() {
const { router: { query: { slug: tag } } } = this.props;
const { router: { query: { slug: slugFromQueryParam } } } = this.props;
const { tagId } = this.props.routingStore;

const slugOrId = slugFromQueryParam || tagId;

return (
<Query query={tagQuery} variables={{ slugOrId: tag }}>
<Query query={tagQuery} variables={{ slugOrId }}>
{({ error, data }) => {
if (error) {
console.error("WithTag query error:", error); // eslint-disable-line no-console
Expand Down
21 changes: 17 additions & 4 deletions src/lib/apollo/withApolloClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,14 @@ export default function withApolloClient(WrappedComponent) {
class WithApolloClient extends React.Component {
static async getInitialProps(ctx) {
const { Component, router, ctx: { req, res, query, pathname } } = ctx;
const requestPath = req && req.get("request-path");

// Provide the `url` prop data in case a GraphQL query uses it
rootMobxStores.routingStore.updateRoute({ query, pathname });
rootMobxStores.routingStore.updateRoute({ query, pathname, route: router.route });

// If getInitialProps was called without a request object,
// then this was most likely a due to a `pushState` rather than a full page request.
const hasRequestObject = !!req;

let user;
try {
Expand Down Expand Up @@ -107,7 +112,9 @@ export default function withApolloClient(WrappedComponent) {
return {
...wrappedComponentProps,
apolloState,
accessToken: user && user.accessToken
accessToken: user && user.accessToken,
requestPath,
hasRequestObject
};
}

Expand All @@ -120,10 +127,16 @@ export default function withApolloClient(WrappedComponent) {
};

static getDerivedStateFromProps(nextProps) {
const { pathname, query } = nextProps.router;
const { pathname, query, route } = nextProps.router;
const { requestPath, hasRequestObject } = nextProps;

// Update routing store with pathname and query after route change
rootMobxStores.routingStore.updateRoute({ pathname, query });
rootMobxStores.routingStore.updateRoute({ pathname, query, route });

// Set the rewrite path if this was a full page request
if (hasRequestObject) {
rootMobxStores.routingStore.setRewriteRoute(requestPath, route);
}

return null;
}
Expand Down
57 changes: 54 additions & 3 deletions src/lib/stores/RoutingStore.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { action, toJS, observable } from "mobx";
import { Router } from "routes";
import routes, { Router } from "routes";
import { inPageSizes, PAGE_SIZES } from "lib/utils/pageSizes";

/**
Expand All @@ -15,6 +15,20 @@ export default class RoutingStore {
*/
@observable pathname = "";

/**
* The path from the response header "Request-Path".
*
* @type string
*/
@observable requestPath = null;

/**
* The route, which corresponds to the page template
*
* @type string
*/
@observable route = null;

/**
* The query params for the current page (i.e. `{shop: `1234', first: 24}`)
*
Expand All @@ -41,9 +55,44 @@ export default class RoutingStore {
};

@action
updateRoute({ pathname, query }) {
updateRoute({ pathname, query, route }) {
this.pathname = pathname;
this.query = query;
this.route = route;
}

/**
* Set the request path
* @name setRequestPath
* @param {String} path Request pathname
* @returns {undefined} No return value
*/
@action setRequestPath(path) {
this.requestPath = path;
}

/**
* Set a new rewrite route for the browser app that resolves to an internal route.
* This is used to handle rewrite urls from an HTTP proxy by adding a new
* route so the browser-side app can properly resolve that path to a page.
* @name setRewriteRoute
* @param {String} from Path to add a dynamic route for.
* @param {String} to Internal page route, usually in the form of "/"" for home, "/product", "/tag", etc
* @returns {undefined} No return value
*/
setRewriteRoute(from, to) {
this.setRequestPath(from);

if (process.browser) {
// Remove all generated rewrite routes
const routesWithoutRewrites = routes.routes.filter(({ name }) => (
name.startsWith("rewrite-") === false
));
routes.routes = routesWithoutRewrites;

// Add new generated route
routes.add(`rewrite-${from}`, from, to);
}
}

/**
Expand Down Expand Up @@ -80,7 +129,9 @@ export default class RoutingStore {
this.queryString = urlQueryString;

let path;
if (_slug) {
if (this.requestPath) {
path = `${this.requestPath}?${this.queryString}`;
} else if (_slug) {
path = `${this.pathname}/${_slug}?${this.queryString}`;
} else {
path = `${this.pathname}?${this.queryString}`;
Expand Down
11 changes: 11 additions & 0 deletions src/pages/tag.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import withCatalogItems from "containers/catalog/withCatalogItems";
import withTag from "containers/tags/withTag";
import Breadcrumbs from "components/Breadcrumbs";
import ProductGrid from "components/ProductGrid";
import ProductGridEmptyMessage from "components/ProductGrid/ProductGridEmptyMessage";
import ProductGridHero from "components/ProductGridHero";
import ProductGridTitle from "components/ProductGridTitle";
import SharedPropTypes from "lib/utils/SharedPropTypes";
Expand Down Expand Up @@ -54,6 +55,7 @@ export default class TagGridPage extends Component {
after: null
});
}

return null;
}

Expand Down Expand Up @@ -124,6 +126,15 @@ export default class TagGridPage extends Component {
const pageSize = routingStore.query && routingStore.query.limit ? parseInt(routingStore.query.limit, 10) : uiStore.pageSize;
const sortBy = routingStore.query && routingStore.query.sortby ? routingStore.query.sortby : uiStore.sortBy;

if (!tag) {
return (
<ProductGridEmptyMessage
actionMessage="Go Home"
resetLink="/"
/>
);
}

return (
<Fragment>
<Helmet
Expand Down