1 var define = require("comb").define; 2 3 /** 4 * @class Time stamp plugin to support creating timestamp 5 * 6 * @example 7 * 8 * //create your model and register the plugin. 9 * var MyModel = moose.addModel("testTable", { 10 * plugins : [moose.plugins.TimeStampPlugin]; 11 * }); 12 * 13 * //initialize default timestamp functionality 14 * MyModel.timestamp(); 15 * 16 * //Or 17 * 18 * //initialize custom update column 19 * MyModel.timestamp({updated : "myUpdateColumn"}); 20 * 21 * //Or 22 * 23 * //initialize custom created column 24 * MyModel.timestamp({created : "myCreatedColumn"}); 25 * 26 * //Or 27 * 28 * //Set to update the updated column when row is created 29 * MyModel.timestamp({updateOnCreate : true}); 30 * 31 * //Or 32 * 33 * //Set both custom columns 34 * MyModel.timestamp({updated : "myUpdateColumn", created : "myCreatedColumn"}); 35 * 36 * //Or 37 * 38 * //Use all three options! 39 * MyModel.timestamp({ 40 * updated : "myUpdateColumn", 41 * created : "myCreatedColumn", 42 * updateOnCreate : true 43 * }); 44 * 45 * 46 * @name TimeStampPlugin 47 * @memberOf moose.plugins 48 */ 49 module.exports = exports = define(null, { 50 51 static : { 52 /**@lends moose.plugins.TimeStampPlugin*/ 53 54 /** 55 * Adds timestamp functionality to a table. 56 * @param {Object} [options] 57 * @param {String} [options.updated="updated"] the name of the column to set the updated timestamp on. 58 * @param {String} [options.created="created"] the name of the column to set the created timestamp on 59 * @param {Boolean} [options.updateOnCreate=false] Set to true to set the updated column on creation 60 **/ 61 timestamp : function(options) { 62 options = options || {}; 63 var updateColumn = options.updated || "updated"; 64 var createdColumn = options.created || "created"; 65 var updateOnCreate = options.updateOnCreate || false; 66 this.pre("save", function(next) { 67 this[createdColumn] = new Date(); 68 if (updateOnCreate) { 69 this[updateColumn] = new Date(); 70 } 71 next(); 72 }); 73 this.pre("update", function(next) { 74 this[updateColumn] = new Date(); 75 next(); 76 }); 77 } 78 } 79 80 });