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

Offline mode and web app manifest #486

Merged
merged 23 commits into from
Nov 28, 2018
Merged
Show file tree
Hide file tree
Changes from 20 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
56 changes: 53 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,12 @@
"devDependencies": {
"@magento/directive-parser": "^0.1.1",
"@magento/eslint-config": "^1.2.3",
"@storybook/addon-actions": "^3.4.2",
"@storybook/addons": "^3.4.6",
"@storybook/react": "^3.4.2",
"apollo-boost": "^0.1.15",
"apollo-cache-inmemory": "^1.3.5",
"apollo-cache-persist": "^0.1.1",
"apollo-client": "^2.4.2",
"apollo-link-context": "^1.0.9",
"apollo-server": "^2.0.5",
Expand All @@ -63,6 +66,7 @@
"chalk": "^2.4.1",
"chokidar": "^2.0.4",
"contains-path": "^1.0.0",
"copy-webpack-plugin": "^4.6.0",
"coveralls": "^3.0.1",
"cross-env": "^5.2.0",
"css-loader": "^1.0.0",
Expand Down
24 changes: 21 additions & 3 deletions packages/peregrine/src/Router/MagentoRouteHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,34 @@ export default class MagentoRouteHandler extends Component {
}
};

// TODO: Add the ability to customize the cache name
async addToCache(urls) {
const myCache = await window.caches.open(
`workbox-runtime-${location.origin}/`
);
await myCache.addAll(urls);
}

componentDidMount() {
mountedInstances.add(this);
this.getRouteComponent(this.props.location.pathname);
this.getRouteComponent();
}

componentDidUpdate() {
const { props, state } = this;
const { pathname } = props.location;
const isKnown = state.componentMap.has(pathname);

if (!isKnown) {
this.getRouteComponent(pathname);
// `NOTFOUND` component needs a unique id
// currently it is set to -1
const isNotFoundComponent = isKnown
? state.componentMap.get(pathname).id === -1
: false;

const shouldReloadRoute = isNotFoundComponent && navigator.onLine;

if (!isKnown || shouldReloadRoute) {
this.getRouteComponent();
}
}

Expand Down Expand Up @@ -88,6 +104,8 @@ export default class MagentoRouteHandler extends Component {
return;
}

this.addToCache([pathname]);

this.setState(({ componentMap }) => ({
componentMap: new Map(componentMap).set(pathname, {
RootComponent,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,48 @@ const urlResolverRes = (type, id) =>
}
});

const NotFoundManifest = {
NotFound: {
rootChunkID: -1,
rootModuleID: 100,
pageTypes: ['NOTFOUND']
}
};

const mockManifest = {
Category: {
rootChunkID: 2,
rootModuleID: 100,
pageTypes: ['CATEGORY']
},
Product: {
rootChunkID: 1,
rootModuleID: 99,
pageTypes: ['PRODUCT']
},
...NotFoundManifest
};

const cachedResponse = JSON.stringify({
'foo-bar.html': {
...JSON.parse(urlResolverRes('PRODUCT'))
}
});

const isOnline = _value => ({
get: () => _value,
set: v => (_value = v)
});

Object.defineProperty(navigator, 'onLine', isOnline(true));

function clearLocalStorage(item) {
localStorage.setItem(item, null);
}

beforeEach(() => {
navigator.onLine = true;
clearLocalStorage('urlResolve');
document.body.innerHTML = '';
resolveUnknownRoute.preloadDone = false;
fetch.resetMocks();
Expand All @@ -18,14 +59,67 @@ test('Preload path: resolves directly from preload element', async () => {
'<script type="application/json" id="url-resolver">{ "type": "PRODUCT", "id": "VA-123" }</script>';
const res = await resolveUnknownRoute({
route: 'foo-bar.html',
apiBase: 'https://store.com'
apiBase: 'https://example.com'
});
expect(res).toMatchObject({
type: 'PRODUCT',
id: 'VA-123'
});
});

test('returns NOTFOUND when offline and requested content is not in cache ', async () => {
navigator.onLine = false;

fetch.mockResponseOnce(JSON.stringify(mockManifest));
const res = await resolveUnknownRoute({
route: 'foo-bar.html',
apiBase: 'https://store.com',
__tmp_webpack_public_path__: 'https://dev-server.com/pub'
});

expect(res).toHaveProperty('id', NotFoundManifest.NotFound.rootChunkID);
});

test('stores response of urlResolver in cache', async () => {
fetch.mockResponseOnce(urlResolverRes('PRODUCT'));
fetch.mockResponseOnce(JSON.stringify(mockManifest));

const url = 'foo-bar.html';

await resolveUnknownRoute({
route: url,
apiBase: 'https://store.com',
pcvonz marked this conversation as resolved.
Show resolved Hide resolved
__tmp_webpack_public_path__: 'https://dev-server.com/pub'
});

expect(localStorage.getItem('urlResolve')).not.toBeNull();
});

test('does not call fetchRoute when response is cached', async () => {
localStorage.setItem('urlResolve', cachedResponse);

fetch.mockResponseOnce(JSON.stringify(mockManifest));
await resolveUnknownRoute({
route: 'foo-bar.html',
apiBase: 'https://store.com',
__tmp_webpack_public_path__: 'https://dev-server.com/pub'
});

expect(fetch).toHaveBeenCalledTimes(0);
});

test('calls fetchRoute when response is not cached', async () => {
fetch.mockResponseOnce(urlResolverRes('PRODUCT'));
fetch.mockResponseOnce(JSON.stringify(mockManifest));
await resolveUnknownRoute({
route: 'foo-bar.html',
apiBase: 'https://store.com',
__tmp_webpack_public_path__: 'https://dev-server.com/pub'
});

expect(fetch).toHaveBeenCalledTimes(1);
});

test('urlResolver path: resolve using fetch to GraphQL after one preload', async () => {
fetch.mockResponseOnce(urlResolverRes('PRODUCT', 'VA-11'));
document.body.innerHTML =
Expand Down
47 changes: 45 additions & 2 deletions packages/peregrine/src/Router/resolveUnknownRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,41 @@ export default async function resolveUnknownRoute(opts) {
}

/**
* @description Calls the GraphQL API for results from the urlResolver query
* @description Checks if route is stored in localStorage, if not call `fetchRoute`
* @param {{ route: string, apiBase: string}} opts
* @returns {Promise<{type: "PRODUCT" | "CATEGORY" | "CMS_PAGE"}>}
*/
function remotelyResolveRoute(opts) {
let urlResolve = localStorage.getItem('urlResolve');
urlResolve = JSON.parse(urlResolve);

// If it exists in localStorage, use that value
// TODO: This can be handled by workbox once this issue is resolved in the
// graphql repo: https://github.com/magento/graphql-ce/issues/229
if ((urlResolve && urlResolve[opts.route]) || !navigator.onLine) {
if (urlResolve && urlResolve[opts.route]) {
return new Promise(function(resolve) {
resolve(urlResolve[opts.route].data.urlResolver);
});
} else {
return new Promise(function(resolve) {
resolve({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should be able to use Promise.resolve() here. Alternately, you could make remotelyResolveRoute an async function and just return things directly.

type: 'NOTFOUND',
id: -1
});
});
}
} else {
return fetchRoute(opts);
}
}

/**
* @description Calls the GraphQL API for results from the urlResolver query
* @param {{ route: string, apiBase: string}} opts
* @returns {Promise<{type: "PRODUCT" | "CATEGORY" | "CMS_PAGE"}>}
*/
function fetchRoute(opts) {
const url = new URL('/graphql', opts.apiBase);
return fetch(url, {
method: 'POST',
Expand All @@ -66,5 +96,18 @@ function remotelyResolveRoute(opts) {
})
})
.then(res => res.json())
.then(res => res.data.urlResolver);
.then(res => {
storeURLResolveResult(res, opts);
return res.data.urlResolver;
});
}

// TODO: This can be handled by workbox once this issue is resolved in the
// graphql repo: https://github.com/magento/graphql-ce/issues/229
function storeURLResolveResult(res, opts) {
let urlResolve = localStorage.getItem('urlResolve');
urlResolve = JSON.parse(urlResolve);
urlResolve = urlResolve ? urlResolve : {};
urlResolve[opts.route] = res;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider declaring more than one variable here instead of reusing the same one, so it's easier to read.

const itemString = localStorage.getItem('urlResolve')
const item = JSON.parse(storedRoute) || {}

item[opts.route] = res
localStorage.setItem('urlResolve', JSON.stringify(item))

localStorage.setItem('urlResolve', JSON.stringify(urlResolve));
}
Loading