Skip to content

Commit

Permalink
Moved idb implementation out of service worker. Fixed a few bugs in t…
Browse files Browse the repository at this point in the history
…he review form.
  • Loading branch information
Kate Lovett committed Nov 3, 2018
1 parent ae51fa3 commit 9749e01
Show file tree
Hide file tree
Showing 7 changed files with 131 additions and 76 deletions.
69 changes: 63 additions & 6 deletions app/js/dbhelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*/
// Change this to your server port
const port = 1337;
const dbPromise = idb.open('restaurantReviews', 3, upgradeDb => {
const dbPromise = idb.open("restaurantReviews", 3, upgradeDb => {
switch(upgradeDb.oldVersion) {
case 0: upgradeDb.createObjectStore("restaurantData", {keyPath: "id"});
case 1: upgradeDb.createObjectStore("reviewData", {keypath: "id"}).createIndex("restaurant_id", "restaurant_id");
Expand Down Expand Up @@ -61,7 +61,7 @@ class DBHelper {
* Fetch a restaurant by its ID.
*/
static fetchRestaurantById(id, callback) {
console.log(`In fetchRestaurantsById - id: ${id}, callback: ${callback}`);
console.log(`In fetchRestaurantsById - id: ${id}`);
// fetch all restaurants with proper error handling.
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
Expand Down Expand Up @@ -201,15 +201,16 @@ class DBHelper {
static fetchReviewsById(id) {
let requestURL = DBHelper.DATABASE_URL_REVIEWS + "/?restaurant_id=" + id;
console.log(`In DBHelper.fetchReviewsById - request: ${requestURL}, id: ${id}`);
fetch(requestURL, {method: "GET"})
return fetch(requestURL, {method: "GET"})
.then(function(response) {
console.log("response: ", response);
if (response.ok) return response.json();

//throw new Error("Fetch response Error in fetchReviewsBy...ID")
})
.then(function(reviewData) {
// If fetch successful
console.log(reviewData);
console.log("reviewData: ", reviewData);
//dbPromise.putReviews(reviewData);
return reviewData;
})
Expand Down Expand Up @@ -242,7 +243,8 @@ class DBHelper {
let updaterestaurant = restaurants[0];
if (!updaterestaurant) return;
// Update restaurant with new data
Object.keys(update).forEach(key => { updaterestaurant[key] = update[key]; });
let keys = Object.keys(update)
keys.forEach(key => { updaterestaurant[key] = update[key]; });

// Store updated information back in idb
dbPromise.then(function(db) {
Expand All @@ -263,7 +265,8 @@ class DBHelper {
let updaterestaurant = value.data;
if (!updaterestaurant) return;
// Update restaurant wiht new data
Object.keys(update).forEach(key => { updaterestaurant[key] = update[key] });
let keys = Object.keys(update)
keys.forEach(key => { updaterestaurant[key] = update[key] });

// Store updated information back in idb
dbPromise.then(function(db) {
Expand Down Expand Up @@ -365,4 +368,58 @@ class DBHelper {
//callback(null, null);
}

// IDB Functionality ------

/*
* Function to check idb for restaurant information
*/
static idbRestaurantRequest() {
return dbPromise.then(function(db) {
return db.transaction('restaurantData').objectStore('restaurantData').get(id);
})
.then(function(data) {
return (data && data.data) || fetch(event.request)
.then(function(response) {
return dbPromise
.then(function(db) {
db.transaction('restaurantData', 'readwrite').objectStore('restaurantData').put({ id: id, data: response.json() });
return response.json();
});
});
})
.then(function(endResponse) { return new Response(JSON.stringify(endResponse)); })
.catch(function(error) { console.log(`In DBHelper.idbRestaurantRequest, error: ${error.message}`); })
}

/*
* Function to check idb for review information
*/
static idbReviewRequest() {
return dbPromise.then(function(db) {
return db.transaction('reviewData').objectStore('reviewData').index('restaurant_id').getAll(id);
})
.then(function(data) {
return (data && data.data) || fetch(event.request)
.then(function(response) {
return dbPromise
.then(function(db) {
let store = db.transaction('reviewData', 'readwrite').objectStore('reviewData');
let r = response.json();
r.forEach(function(review) {
store.put({id: review.id, 'restaurant_id': review.restaurant_id, data: review});
})
return r;
});
});
})
.then(function(endResponse) {
if(endResponse[0].data) {
let formatted = endResponse.map(review => review.data);
return new Response(JSON.stringify(formatted));
}
return new Response(JSON.stringify(endResponse));
})
.catch(function(error) { console.log(`In apiFetch catch-reviewData, error: ${error.message}`); })
}

}
51 changes: 45 additions & 6 deletions app/js/restaurant_info.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ fetchRestaurantFromURL = (callback) => {
callback(error, null);
} else {
DBHelper.fetchRestaurantById(id, (error, restaurant) => {
//console.log(restaurant);
self.restaurant = restaurant;
if (!restaurant) {
console.error(error);
Expand Down Expand Up @@ -74,7 +75,7 @@ fillRestaurantHTML = (restaurant = self.restaurant) => {
image.srcset = `/img/${restaurant.id}@1x.webp 300w,
/img/${restaurant.id}@2x.webp 600w,
/img/${restaurant.id}@3x.webp 900w`;
image.alt = restaurant.alt_text;
image.alt = `Image of ${restaurant.name} restaurant`;

const cuisine = document.getElementById('restaurant-cuisine');
cuisine.innerHTML = restaurant.cuisine_type;
Expand All @@ -86,7 +87,7 @@ fillRestaurantHTML = (restaurant = self.restaurant) => {
// fill reviews
//fillReviewsHTML();
console.log(`In fillRestaurantHTML, about to call fetch then fill with id: ${restaurant.id}`);
DBHelper.fetchReviewsById(restaurant.id).then(fillReviewsHTML(reviews));
DBHelper.fetchReviewsById(restaurant.id).then(fillReviewsHTML);
}

/*
Expand Down Expand Up @@ -141,7 +142,7 @@ fillRestaurantHoursHTML = (operatingHours = self.restaurant.operating_hours) =>
/*
* Create all reviews HTML and add them to the webpage.
*/
fillReviewsHTML = (reviews) => {
fillReviewsHTML = (reviews = self.restaurant.reviews) => {
console.log("In fillReviewsHTML ", reviews);
const container = document.getElementById('reviews-container');
const title = document.createElement('h3');
Expand All @@ -156,7 +157,7 @@ fillReviewsHTML = (reviews) => {

if (!reviews) {
const noReviews = document.createElement('h3');
noReviews.innerHTML = 'No reviews yet!';
noReviews.innerHTML = '<br>No reviews yet!<br>';
container.appendChild(noReviews);
return;
}
Expand All @@ -178,7 +179,7 @@ createReviewHTML = (review) => {
li.appendChild(name);

const date = document.createElement('p');
date.innerHTML = review.date;
date.innerHTML = new Date(review.createdAt).toLocaleDateString();
li.appendChild(date);

const rating = document.createElement('p');
Expand Down Expand Up @@ -323,8 +324,46 @@ handleSubmit = (e) => {
//console.log("in handleSubmit");
let id = self.restaurant.id;
let name = document.getElementById("name").value;
let rating = document.getElementById("rating").value + 0;
let rating = document.getElementById("rating").value - 0;
let comments = document.getElementById("comments").value;
// Add the new review to the reviews list
const ul = document.getElementById('reviews-list');

// Put new review in reviews list on site ---
const li = document.createElement('li');
const newName = document.createElement('p');
newName.id = "reviewer-name";
newName.innerHTML = name;
li.appendChild(newName);

const date = document.createElement('p');
//let now = Date.now();
date.innerHTML = "Date";// TODO, sort this mess out : now.toLocaleDateString();
li.appendChild(date);

const newRating = document.createElement('p');
newRating.innerHTML = `Rating: ${rating}`;
li.appendChild(newRating);

const stars = document.createElement('p');
var starString = "";
for (i = 0; i < rating; i++){
starString += "&#9733 ";
}
//console.log("starString ", starString);
stars.innerHTML = starString;
li.appendChild(stars);

const line = document.createElement('hr');
li.appendChild(line);

const newComments = document.createElement('p');
newComments.id = "reviewer-comments";
newComments.innerHTML = comments;
li.appendChild(newComments);
//---

ul.appendChild(li);

DBHelper.saveReview(id, name, rating, comments, Date.now());
// Get rid of the form
Expand Down
2 changes: 1 addition & 1 deletion app/js/swregister.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Registering the Service Worker
if ("serviceWorker" in navigator) {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(function(registration) {
console.log('Registration successful, scope is: ', registration.scope);
Expand Down
79 changes: 19 additions & 60 deletions app/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*/

// Include DBHelper functions for fetching restaurants and putting in indexedDB
self.importScripts('./js/dbhelper.js', './js/idb.js');
self.importScripts('js/dbhelper.js', 'js/idb.js');

// Cache Information
var myCache = 'restaurantReview_301';
Expand All @@ -20,24 +20,24 @@ var cacheFiles = [
];

// IDB Information
const dbPromise = idb.open('restaurantReviews', 3, upgradeDb => {
switch(upgradeDb.oldVersion) {
case 0: upgradeDb.createObjectStore('restaurantData', {keyPath: 'id'});
case 1: upgradeDb.createObjectStore('reviewData', {keypath: 'id'}).createIndex('restaurant_id', 'restaurant_id');
case 2: upgradeDb.createObjectStore('updateData', {keyPath: 'id', autoIncrement: true});
}
});
//const dbPromise = idb.open('restaurantReviews', 3, upgradeDb => {
// switch(upgradeDb.oldVersion) {
// case 0: upgradeDb.createObjectStore('restaurantData', {keyPath: 'id'});
// case 1: upgradeDb.createObjectStore('reviewData', {keypath: 'id'}).createIndex('restaurant_id', 'restaurant_id');
// case 2: upgradeDb.createObjectStore('updateData', {keyPath: 'id', autoIncrement: true});
// }
//});

/*
* Event Listener for install - caching the files
*/
self.addEventListener('install', function(event) {
console.log('In eventListener for install, event: ', event)
console.log('In eventListener for install')
event.waitUntil(caches.open(myCache)
.then(function(cache) {
return cache.addAll(cacheFiles)
.then(function() { console.log('Cache worked!'); } )
.catch(function(error) { console.log('Caching failed, error: ', error); } );
.then(function() { console.log('Cache worked!'); })
.catch(function(error) { console.log('Caching failed, error: ', error); });
}));
});

Expand All @@ -46,7 +46,7 @@ self.addEventListener('install', function(event) {
* Event Listener for fetch - pull files from cache and update with fetch is possible
*/
self.addEventListener('fetch', function(event) {
console.log('In eventListener for fetch, event: ', event);
console.log('In eventListener for fetch, event');
// Separating fetch requests
let requestURL = new URL(event.request.url);
if (requestURL.port === '1337') {
Expand All @@ -67,67 +67,26 @@ self.addEventListener('fetch', function(event) {
});

function apiFetch(event, id) {
console.log(`In apiFetch - event: ${event} id: ${id}`);
if (event.request.method == 'POST' || event.request.method == 'PUT') {
console.log('In apiFetch');
if (event.request.method != 'GET') {
// Post & Put methods are not cached. Process request without further action.
return fetch(event.request)
.then(function(response) { return response.json(); });
}

// Restaurant and Review information are now being kept in separate stores: restaurantData & reviewData

// Restaurant Request -------------------------------------------------------------------------------
// Restaurant Request
if(event.request.url.indexOf('restaurants') > -1) {
event.respondWith(dbPromise.then(function(db) {
return db.transaction('restaurantData').objectStore('restaurantData').get(id);
})
.then(function(data) {
return (data && data.data) || fetch(event.request)

.then(function(response) {
return dbPromise

.then(function(db) {
db.transaction('restaurantData', 'readwrite').objectStore('restaurantData').put({ id: id, data: response.json() });
return response.json();
});
});
})
.then(function(endResponse) { return new Response(JSON.stringify(endResponse)); })
.catch(function(error) { console.log(`In apiFetch catch-restaurantData, error: ${error.message}`); }));
event.respondWith(DBHelper.idbRestaurantRequest());
}

// Review Request -----------------------------------------------------------------------------------
event.respondWith(dbPromise.then(function(db) {
return db.transaction('reviewData').objectStore('reviewData').index('restaurant_id').getAll(id);
})
.then(function(data) {
return (data && data.data) || fetch(event.request)

.then(function(response) {
return dbPromise

.then(function(db) {
let store = db.transaction('reviewData', 'readwrite').objectStore('reviewData');
response.json().forEach(function(review) {
store.put({id: review.id, 'restaurant_id': review.restaurant_id, data: review});
})
return response.json();
});
});
})
.then(function(endResponse) {
if(endResponse[0].data) {
let formatted = endResponse.map(review => review.data);
return new Response(JSON.stringify(formatted));
}
return new Response(JSON.stringify(endResponse));
})
.catch(function(error) { console.log(`In apiFetch catch-reviewData, error: ${error.message}`); }));
// Review Request
event.respondWith(DBHelper.idbReviewRequest());
}

function cacheFetch(event, request) {
console.log(`In cacheFetch - event: ${event} request: ${request}`);
console.log('In cacheFetch');
// Check the cache before fetching.
// If fetched, store in the cache.
event.respondWith(caches.match(request))
Expand Down
Loading

0 comments on commit 9749e01

Please sign in to comment.