forked from Netflix/falcor-router-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recommendation-service.js
71 lines (65 loc) · 2.79 KB
/
recommendation-service.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
var Promise = require('promise');
var PouchDB = require('pouchdb');
var path = require('path');
var recommendationsDB = new PouchDB(path.join(__dirname, 'recommendations_db'));
var batch = require('./batch');
// genrelist service
function RecommendationsService() {}
RecommendationsService.prototype = {
getGenreList: function(userId) {
userId = (userId || 'all').toString();
var getGenreLists = batch(function(userIds) {
return recommendationsDB.allDocs({
keys: userIds.map(function(x) { return x.toString(); }),
include_docs: true
}).then(function(dbResponse) {
var genreLists = {};
dbResponse.rows.forEach(function(row) {
genreLists[row.key] = row;
});
return genreLists;
});
});
return getGenreLists([userId]).then(function(genreLists) {
return genreLists[userId].doc.recommendations;
});
},
addTitleToGenreList: function(userId, genreIndex, titleId) {
userId = userId.toString();
return recommendationsDB.get(userId)
.then(function(response) {
if (!response.recommendations[genreIndex]) {
return Promise.reject(new Error("genrelist does not exist at index " + genreIndex));
}
var titlesLength = response.recommendations[genreIndex].titles.push(titleId);
return recommendationsDB.put({
_id: userId,
_rev: response._rev,
recommendations: response.recommendations
}).then(function() {
return titlesLength;
});
});
},
removeTitleFromGenreListByIndex: function(userId, genreIndex, titleIndex) {
userId = userId.toString();
return recommendationsDB.get(userId)
.then(function(response) {
if (!response.recommendations[genreIndex]) {
return Promise.reject(new Error("genrelist does not exist at index " + genreIndex));
}
var removedTitleId = response.recommendations[genreIndex].titles.splice(titleIndex, 1)[0];
return recommendationsDB.put({
_id: userId,
_rev: response._rev,
recommendations: response.recommendations
}).then(function() {
return {
titleId: removedTitleId,
length: response.recommendations[genreIndex].titles.length
};
});
});
}
};
module.exports = new RecommendationsService();