Skip to content

Commit

Permalink
Committing progress on stage 3. Still debugging.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kate Lovett committed Nov 3, 2018
1 parent e472f77 commit 08a2fb4
Show file tree
Hide file tree
Showing 15 changed files with 1,975 additions and 439 deletions.
32 changes: 30 additions & 2 deletions app/css/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ nav {
line-height: 2em;
background-color: #252831;
text-align:center;
/*max-width:900px;*/
}
nav h1 {
margin: auto;
Expand Down Expand Up @@ -128,6 +127,16 @@ nav h1 a {
display: none;
}

.favButton {
background-image: none;
border: none;
font-size: 20pt;
}

.favSpan[aria-pressed=true] {
color : orange;
}

/* ====================== Restaurant Listing ====================== */
#restaurants-list {
background-color: #f3f3f3;
Expand Down Expand Up @@ -251,6 +260,19 @@ nav h1 a {
padding-top: 5px;
line-height:1.5em;
}
#reviewButton, #submitReview {
background-color: #252831;
border-bottom: 3px solid #eee;
color: #fff;
font-size: 12pt;
margin: 0 auto;
padding: 15px;
text-align: center;
text-decoration: none;
text-transform: uppercase;
display: flex;
justify-content: center;
}
#reviews-list {
padding:0px;
}
Expand Down Expand Up @@ -284,7 +306,13 @@ nav h1 a {
width: 100%;
border-radius: 10px 0px 0px 0px;
}
#reviewer-comments {
#reviewer-comments, input {
padding-left: 15px;
padding-right: 15px;
}

label {
padding : 10px;
}


225 changes: 205 additions & 20 deletions app/js/dbhelper.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,67 @@
/*
* Constants
*/
// Change this to your server port
const port = 1337;
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});
}
});

/*
* Common database helper functions.
*/

class DBHelper {

/*
* Database URL.
* Change this to restaurants location on your server.
* Database URLs.
*/
static get DATABASE_URL() {
const port = 1337 // Change this to your server port
return `http://localhost:${port}/restaurants`;
}
static get DATABASE_URL() { return `http://localhost:${port}/restaurants`; }

static get DATABASE_URL_REVIEWS() { return `http://localhost:${port}/reviews`; }

/*
* Fetch all restaurants.
*/
static fetchRestaurants(callback) {
console.log(`In fetchRestaurants - callback: ${callback}`);
let requestURL = DBHelper.DATABASE_URL;
// console.log(`Request URL: ${requestURL}`);
// Fetch restaurant data from server
fetch(DBHelper.DATABASE_URL)
fetch(requestURL, {method: "GET"})
.then(function(response) {
// If response returns ok, return json of restaurant data
if (response.ok) return response.json();

// If not returned, there is an error - or offline mode
throw new Error("Fetch repsponse Error");
// throw new Error("Fetch response Error in fetchRestaurants");
})
.then(function(restaurantData) {
callback(null, restaurantData);
})
.catch(function(error) {
console.log("In fetchRestaurants catch, error:", error.message);
// Retrieve data from IndexedDB
idb.open('restaurantReviews', 1)
.then(db => {
return db.transaction("restaurantData")
.objectStore("restaurantData")
.getAll();
})
.then(restaurantData => {
callback(null,restaurantData);
});
console.log("In fetchRestaurants catch, error: ", error.message);
// // Retrieve data from IndexedDB
// idb.open('restaurantReviews', 1)
// .then(db => {
// return db.transaction("restaurantData")
// .objectStore("restaurantData")
// .getAll();
// })
// .then(restaurantData => {
// callback(null,restaurantData);
// });
});
}

/*
* Fetch a restaurant by its ID.
*/
static fetchRestaurantById(id, callback) {
console.log(`In fetchRestaurantsById - id: ${id}, callback: ${callback}`);
// fetch all restaurants with proper error handling.
DBHelper.fetchRestaurants((error, restaurants) => {
if (error) {
Expand All @@ -63,6 +77,7 @@ class DBHelper {
});
}


/*
* Fetch restaurants by a cuisine type with proper error handling.
*/
Expand Down Expand Up @@ -180,4 +195,174 @@ class DBHelper {
return marker;
}

/*
* Fetch reviews by restaurant ID
*/
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"})
.then(function(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);
//dbPromise.putReviews(reviewData);
return reviewData;
})
.catch(function(error) {
console.log("In fetchReviewsBy...ID catch, error:", error.message);
// // Error handling
// console.log(`Error in fetch reviews by ID: ${error}, checking idb...`);
// if (idbReviews.length < 1) return null;
// return idbReviews;
});
}

/*
* Function to update the Restaurant Data stored in idb store: restaurantData
*/
static updateRestaurantCache(id, update) {
console.log(`In updateRestaurantCache - id: ${id}, update: ${update}`);
let dbPromise = idb.open("restaurantReviews");

// Update all restaurant data
dbPromise.then(function(db) {
//let restaurantStore =
db.transaction("restaurantData", "readwrite").objectStore("restaurantData").get("-1")
.then(function(value) {
if(!value) {
console.log("No value, update all, in updateRestaurantCache");
return;
}
let restaurants = value.data.filter(r => r.id === id);
let updaterestaurant = restaurants[0];
if (!updaterestaurant) return;
// Update restaurant with new data
Object.keys(update).forEach(key => { updaterestaurant[key] = update[key]; });

// Store updated information back in idb
dbPromise.then(function(db) {
let trans = db.transaction("restaurantData", "readwrite").objectStore("restaurantData").put({id:"-1", data: value.data});
return trans.complete;
})
})
})

// Update individual restaurant data
dbPromise.then(function(db) {
db.transaction("restaurantData", "readwrite").objectStore("restaurantData").get(id + "")
.then(function(value) {
if(!value) {
console.log("No value, update individual, in updateRestaurantCache");
return;
}
let updaterestaurant = value.data;
if (!updaterestaurant) return;
// Update restaurant wiht new data
Object.keys(update).forEach(key => { updaterestaurant[key] = update[key] });

// Store updated information back in idb
dbPromise.then(function(db) {
let trans = db.transaction("restaurantData", "readwrite").objectStore("restaurantData").put({id: id + "", data: value.data});
return trans.complete;
})
})
})
}

/*
* Function to update the Reviews Data stored in idb store: reviewData
*/
static updateReviewCache(id, update) {
console.log(`In updateReviewCache - id: ${id}, update: ${update}`);
let dbPromise = idb.open("restaurantReviews");

dbPromise.then(function(db) {
let trans = db.transaction("reviewData", "readwrite").objectStore("reviewData").put({id: Date.now(), "restaurant_id": id, data: update});
return trans.complete;
})
}

/*
* Function to update data being held in idb for updates, store: updateData
* Updated data is put in this store regardless of on/off-line status.
*/
static addToUpdateQueue(url, method, update) {
console.log(`In addToUpdateQueue - url: ${url}, method: ${method}, update: ${update}`);
let dbPromise = idb.open("restaurantReviews");
dbPromise.then(function(db) {
db.transaction("updateData", "readwrite").objectStore("updateData").put({ data: { url, method, update } })
})
.catch(function(error) {
console.log("In addToUpdateQueue catch, error: ", error.message);
})
// TODO : attempt push of updates
.then(DBHelper.pushUpdates());
}

/*
* Function to push updates in the idb update store to the server.
*/
static pushUpdates() {
console.log(`In pushUpdates`);
let dbPromise = idb.open("restaurantReviews");
dbPromise.then(function(db) {
db.transaction("updateData", "readwrite").objectStore("updateData").openCursor()
.then(function(cursor) {
// No updates, so get outta here!
if(!cursor) return;
let update = cursor.value.data;

// check for bad records? See in testing

let params = { body: JSON.stringify(update.body), method: update.method };

fetch(update.url, params)
.then(function(response) {
// Can't update right now, so get outta here!
if (!response.ok) return;
})
.then(function() {
// Response came back ok!
db.transaction("updateData", "readwrite").objectStore("updateData").openCursor()
.then(function(cursor) {
cursor.delete()
// Recursive call to push next update record. Will retrun in next call if empty.
.then(function() {
console.log("Record deleted, calling next...");
DBHelper.pushUpdates();
})
})
})
})
.catch(function(error) {
console.log("In pushUpdates catch, error: ", error.message);
return;
})
})
}

/*
* Function for saving a new review.
*/
static saveReview(id, name, rating, comments, date/*, callback*/) {
let url = `${DBHelper.DATABASE_URL_REVIEWS}`;
let method = "POST";
let body = {
restaurant_id: id,
name: name,
rating: rating,
comments: comments,
createdAt: date
};
console.log(`In saveReview - url: ${url}, method: ${method}, body: ${body}`);
DBHelper.updateReviewCache(id, body);
DBHelper.addToUpdateQueue(url, method, body);
//callback(null, null);
}

}
Loading

0 comments on commit 08a2fb4

Please sign in to comment.