Loopback automatic creation & modification timestamp

In certain cases, it’s convenience to have automatic creation & modification timestamp where system automatically records when and who create/update a record. So far, I find that the most efficient way to do this in Loopback is by utilizing hook feature.

Based on the docs, there are 3 types of hooks provided by loopback based on different layers in API server application:

  1. Remote hook: triggered on remote method invocation
  2. Operation hook: triggered on model operations (CRUD)
  3. Connector hook: triggered on connector level operations (connect/disconnect)

To implement automatic creation & modification timestamp, we can use remote and operation hook by adding code below in the model js, in my case my model js is common/models/product.js

module.exports = function(Product) {
    var app = require('../../server/server')

    // Operation hook to handle the date info
    // Update createdAt on model creation and updatedAt on model update
    Product.observe('before save', function filterProperties(ctx, next) {
        if (ctx.isNewInstance) {
            ctx.instance.createdAt = new Date() 
        } else {
            ctx.data.updatedAt = new Date()
        } next()
    }) 

    // Remote hooks to handle the user info
    // Capture username and put it in createdBy when create API called
    Product.afterRemote('create', function( ctx, modelInstance, next) {
        app.models.Customer.findById(ctx.req.accessToken.userId, function(err, user) {          
            modelInstance.createdBy = user.username next()
        })
    }) 

    // Capture username and put it in updatedBy when update API called 
    Product.afterRemote('upsert', function( ctx, modelInstance, next) { 
        app.models.Customer.findById(ctx.req.accessToken.userId, function(err, user) { 
            modelInstance.updatedBy = user.username next()
        })
    })
}

This implementation of course assumes that authentication is enabled for creation and modification API so it can capture the user ID.

Leave a Reply

Your email address will not be published. Required fields are marked *