Skip to content

Commit

Permalink
Added a useTimestamps plugin (with test), to automatically save a tim…
Browse files Browse the repository at this point in the history
…estamp to a 'createdAt' and 'updatedAt' attribute on any schema.
  • Loading branch information
bnoguchi committed Nov 29, 2010
1 parent a4ec6b4 commit bd04ffd
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 16 deletions.
2 changes: 1 addition & 1 deletion index.js
@@ -1 +1 @@
module.exports = require("./lib/types");
module.exports = require("./lib");
17 changes: 17 additions & 0 deletions lib/index.js
@@ -0,0 +1,17 @@
exports.loadTypes = function () {
var mongoose = arguments[0],
types = Array.prototype.slice.call(arguments, 1);
if (types.length) {
types.forEach( function (type) {
require("./types/" + type).loadType(mongoose);
});
} else {
var files = require("fs").readdirSync(__dirname + "/types");
files.forEach( function (filename) {
var base = filename.slice(0, filename.length-3);
require("./types/" + base).loadType(mongoose);
});
}
};

exports.useTimestamps = require("./plugins/useTimestamps").useTimestamps;
12 changes: 12 additions & 0 deletions lib/plugins/useTimestamps.js
@@ -0,0 +1,12 @@
exports.useTimestamps = function (schema, options) {
schema
.date('createdAt')
.date('updatedAt')
.pre('save', function () {
if (!this.createdAt) {
this.createdAt = this.updatedAt = new Date;
} else {
this.updatedAt = new Date;
}
});
};
15 changes: 0 additions & 15 deletions lib/types/index.js

This file was deleted.

41 changes: 41 additions & 0 deletions tests/useTimestamps.test.js
@@ -0,0 +1,41 @@
var assert = require('assert')
, mongoose = require('mongoose').new()
, document = mongoose.define
, db = mongoose.connect('mongodb://localhost/mongoose_types_tests')
, loadTypes = require("../").loadTypes
, useTimestamps = require("../").useTimestamps;

document('TimeCop')
.email('email')
.plugin(useTimestamps);

module.exports = {
before: function(assert, done){
db.on('connect', function () {
mongoose.TimeCop.remove({}, function () {
done();
});
});
},
'createdAt and updatedAt should be set to the same value on creation': function (assert, done) {
mongoose.TimeCop.create({ email: 'brian@brian.com' }, function (err, cop) {
assert.ok(cop.createdAt instanceof Date);
assert.equal(cop.updatedAt, cop.createdAt);
done();
});
},
'updatedAt should be later than createdAt upon updating': function (assert, done) {
mongoose.TimeCop.first({email: 'brian@brian.com'}, function (err, found) {
found.email = 'jeanclaude@vandamme.com';
setTimeout( function () {
found.save( function (err, updated) {
assert.ok(updated.updatedAt > updated.createdAt);
done();
});
}, 1000);
});
},
teardown: function(){
mongoose.disconnect();
}
};

0 comments on commit bd04ffd

Please sign in to comment.