Skip to content

Commit

Permalink
cache bg sync response
Browse files Browse the repository at this point in the history
  • Loading branch information
eezhal92 committed Oct 12, 2017
1 parent 9368d65 commit 59c3931
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
16 changes: 16 additions & 0 deletions src/lib/request.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { cacheName } from '../sw';

const BASE_API_ENDPOINT = `https://resepku-api.herokuapp.com`;

export function getRecipes() {
Expand All @@ -9,3 +11,17 @@ export function getRecipe(id) {
return fetch(`${BASE_API_ENDPOINT}/recipes/${id}`)
.then(response => response.json());
}

export async function getRecipeAndCache(id) {
const request = new Request(`${BASE_API_ENDPOINT}/recipes/${id}`, {
headers: {
'Access-Control-Allow-Origin': '*',
}
});
const response = await fetch(request);
const cache = await caches.open(cacheName);

await cache.put(request, response.clone());

return response.json();
}
6 changes: 3 additions & 3 deletions src/sw.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import storage from 'localforage';
import { getRecipe } from './lib/request';
import { getRecipeAndCache } from './lib/request';

const version = 'v1';
const cacheName = `background-sync-demo-${version}`;
export const cacheName = `background-sync-demo-${version}`;

const filesToCache = [
'/',
Expand Down Expand Up @@ -67,7 +67,7 @@ self.addEventListener('activate', (event) => {
const handleLoadRecipeSync = (event) => {
const getAllItems = (payloads) => {
const promises = payloads.map(async (payload) => {
const data = await getRecipe(payload.recipeId);
const data = await getRecipeAndCache(payload.recipeId);

registration.showNotification(`${data.title} is ready!`, {
body: 'View recipe article',
Expand Down

0 comments on commit 59c3931

Please sign in to comment.