Last active
August 29, 2015 14:06
-
-
Save danielstreit/712333643a658cf17bd3 to your computer and use it in GitHub Desktop.
Add a star to a collection given a user
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var addStar = function(data) { | |
return $http({ | |
method: 'POST', | |
url: '/api/collection/addStar', | |
data: data | |
}).then(function(response) { | |
return response.data; | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If the provided user has not already starred this | |
// collection, adds a star to the collection | |
// | |
// Expects data to have _id and user properties: | |
// { | |
// _id: the collection to add to | |
// user: [ | |
// { | |
// provider: String, | |
// id: String, | |
// fullName: String, | |
// givenName: String | |
// } | |
// ] | |
// } | |
// Returns a promise that resolves to the updated collections | |
mongo.addStar = function(data) { | |
// Stringify the user | |
// This should be unique to every user | |
var userString = data.user.provider + data.user.id; | |
return Collection.findByIdAndUpdate(data._id, { | |
$addToSet: { userStars: userString } | |
}).exec() | |
.then(function(collection) { | |
var update = {}; | |
update._id = collection._id; | |
update.stars = collection.userStars.length; | |
return mongo.update(update); | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// add a star to a collection | |
// this will check if the given user has already stared the collection | |
// and if not, add the user to userStars and increment stars. | |
// responds with the collection, updated or not | |
app.post('/api/collection/addStar', function(req, res) { | |
mongo.addStar(req.body).then(function(collection) { | |
res.end(JSON.stringify(collection)); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment