Add Created By, Updated By, Created Date, Updated Date to Model via Mixin in Loopback

Sunil K Samanta
Sep 6, 2018 · 2 min read

Adding a created by, created date and updated by, updated date is always needed in Models. So why don’t we use a common Mixin for that.

We’ll create a Mixin which will do the job for your Models without copying and pasting the same code in every model.

READ =:> MySql Like Auto Increment Numeric Primary Key For Loopback with MongoDB

Create a file named “created-modified-injection.js” in common/mixins/ folder. and add the bellow code

//created-modified-injection.jsmodule.exports = function(Model, options) {
'use strict';
Model.defineProperty('created_by', {type: Number});
Model.defineProperty('updated_by', {type: Number});
Model.defineProperty('created_date', {type: Date});
Model.defineProperty('updated_date', {type: Date});
Model.observe('before save', function event(ctx, next) {
const token = ctx.options && ctx.options.accessToken;
const userId = token && token.userId;
let date = new Date();
if (ctx.instance) {
if (ctx.isNewInstance) {
ctx.instance.created_by = ctx.instance.created_by || userId;
ctx.instance.created_date = date;
}else{
ctx.instance.updated_by = ctx.instance.updated_by || userId;
ctx.instance.updated_date = date;
}
}
next();
});
};

This Will add created_by, created_date at the time of creating a new instance of the model and will add updated_by, updated_date while updating the instance in every model you enable the mixin in.

Now Enable the Mixin in the Model by adding the bellow property in your model.json files

"mixins": {
"CreatedModifiedInjection": true
},

That’s all! Comment if you have anything in mind.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade