Added message list method

This commit is contained in:
Chris Blanchard 2015-08-07 01:06:40 +01:00
parent cf29e50842
commit 6271d96133
2 changed files with 53 additions and 9 deletions

View file

@ -12,7 +12,15 @@ var messageSchema = new Schema({
createdAt: { type: Date, default: Date.now, required: true }
});
messageSchema.index({ createdAt: -1 });
messageSchema.index({ createdAt: 1 });
// Class Methods
messageSchema.statics.list = function (options, callback) {
}
// Instance Methods
messageSchema.methods.toJson = function () {
return {
@ -23,4 +31,9 @@ messageSchema.methods.toJson = function () {
};
};
messageSchema.statics.list = function (callback) {
return this.find().sort({createdAt: 1}).limit(30).exec(callback);
};
module.exports = mongoose.model('message', messageSchema);

View file

@ -3,20 +3,18 @@
var helper = require("./helpers/index.js");
var Message = helper.Message;
var assert = require("chai").assert;
var async = require("async");
describe("Message Model", function () {
var user;
before(function (done) {
helper.clearDb(done);
});
after(function (done) {
helper.clearDb(done);
});
beforeEach(function () {
user = helper.createUser();
helper.clearDb(done);
});
afterEach(function (done) {
helper.clearDb(done);
});
describe(".create", function () {
@ -38,4 +36,37 @@ describe("Message Model", function () {
});
});
});
describe(".list", function () {
before(function (done) {
var instructions = [helper.clearDb.bind(null)];
var create = function (content) {
return function (callback) {
Message.create({
author: {
username: user.username,
avatar: user.avatar
},
content: content
}, callback);
}
};
for (var i = 0; i < 31; i++) {
instructions.push(create(i));
}
async.series(instructions, done);
});
it ("lists last 30 messages with oldest first", function (done) {
Message.list(function (error, messages) {
if (error) return done(error);
assert.equal(messages.length, 30);
assert.isTrue(messages.reduce(function (acc, message, index, arr) {
if (index === 0) return true;
if (acc === false) return false;
return arr[index - 1].createdAt < message.createdAt;
}));
done();
});
});
});
});