Adding action summaries function to actions model.

This commit is contained in:
David Jay
2016-11-08 15:21:52 -05:00
parent 12aa9c6260
commit eb00e63a41
2 changed files with 55 additions and 1 deletions
+31 -1
View File
@@ -28,7 +28,7 @@ ActionSchema.statics.findById = function(id) {
};
/**
* Finds users in an array of ids.
* Finds actions in an array of ids.
* @param {String} ids array of user identifiers (uuid)
*/
ActionSchema.statics.findByItemIdArray = function(item_ids) {
@@ -37,6 +37,36 @@ ActionSchema.statics.findByItemIdArray = function(item_ids) {
});
};
/**
* Returns summaries of actions for an array of ids
* @param {String} ids array of user identifiers (uuid)
*/
ActionSchema.statics.getActionSummaries = function(item_ids) {
return ActionSchema.statics.findByItemIdArray(item_ids).then((rawActions) => {
// Create an object with a count of each action type for each item
const actionSummaries = rawActions.reduce((actionObj, action) => {
if (!actionObj[action.item_id]) {
actionObj[action.item_id] = {
type: action.action_type,
count: 1,
current_user: false //Corrent this later when we have authentication
};
} else {
actionObj[action.item_id].count ++;
}
return actionObj;
}, {});
// Return an array extracted from the actionSummaries object
return Object.keys(actionSummaries).reduce((actions, key) => {
let actionSummary = actionSummaries[key];
actionSummary.item_id = key;
actions.push(actionSummary);
return actions;
}, []);
});
};
const Action = mongoose.model('Action', ActionSchema);
module.exports = Action;
+24
View File
@@ -15,6 +15,9 @@ describe('Action: models', () => {
}, {
action_type: 'flag',
item_id: '456'
}, {
action_type: 'flag',
item_id: '123'
}]).then((actions) => {
mockActions = actions;
});
@@ -32,7 +35,28 @@ describe('Action: models', () => {
describe('#findByItemIdArray()', () => {
it('should find an array of actions from an array of item_ids', () => {
return Action.findByItemIdArray(['123', '456']).then((result) => {
expect(result).to.have.length(3);
});
});
});
describe('#getActionSummaries()', () => {
it('should return properly formatted summaries from an array of item_ids', () => {
return Action.getActionSummaries(['123', '789']).then((result) => {
expect(result).to.have.length(2);
const sorted = result.sort((a, b) => a.count - b.count);
expect(sorted[0]).to.deep.equal({
type: 'like',
count: 1,
item_id: '789',
current_user: false
});
expect(sorted[1]).to.deep.equal({
type: 'flag',
count: 2,
item_id: '123',
current_user: false
});
});
});
});