Skip to content
Closed
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
75 changes: 57 additions & 18 deletions scripts/FriendlyEats.Data.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,37 +16,76 @@
'use strict';

FriendlyEats.prototype.addRestaurant = function(data) {
/*
TODO: Implement adding a document
*/
var collection = firebase.firestore().collection('restaurants');
return collection.add(data);
};

FriendlyEats.prototype.getAllRestaurants = function(render) {
/*
TODO: Retrieve list of restaurants
*/
var query = firebase.firestore()
.collection('restaurants')
.orderBy('avgRating', 'desc')
.limit(50);
this.getDocumentsInQuery(query, render);
};

FriendlyEats.prototype.getDocumentsInQuery = function(query, render) {
/*
TODO: Render all documents in the provided query
*/
query.onSnapshot(function(snapshot) {
if (!snapshot.size) return render();

snapshot.docChanges.forEach(function(change) {
if (change.type === 'added') {
render(change.doc);
}
});
});
};

FriendlyEats.prototype.getRestaurant = function(id) {
/*
TODO: Retrieve a single restaurant
*/
return firebase.firestore().collection('restaurants').doc(id).get();
};

FriendlyEats.prototype.getFilteredRestaurants = function(filters, render) {
/*
TODO: Retrieve filtered list of restaurants
*/
var query = firebase.firestore().collection('restaurants');

if (filters.category !== 'Any') {
query = query.where('category', '==', filters.category);
}

if (filters.city !== 'Any') {
query = query.where('city', '==', filters.city);
}

if (filters.price !== 'Any') {
query = query.where('price', '==', filters.price.length);
}

if (filters.sort === 'Rating') {
query = query.orderBy('avgRating', 'desc');
} else if (filters.sort === 'Reviews') {
query = query.orderBy('numRatings', 'desc');
}

this.getDocumentsInQuery(query, render);
};

FriendlyEats.prototype.addRating = function(restaurantID, rating) {
/*
TODO: Retrieve add a rating to a restaurant
*/
var collection = firebase.firestore().collection('restaurants');
var document = collection.doc(restaurantID);

return document.collection('ratings').add(rating).then(function() {
return firebase.firestore().runTransaction(function(transaction) {
return transaction.get(document).then(function(doc) {
var data = doc.data();

var newAverage =
(data.numRatings * data.avgRating + rating.rating) /
(data.numRatings + 1);

return transaction.update(document, {
numRatings: data.numRatings + 1,
avgRating: newAverage
});
});
});
});
};