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:
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.
TL;DR Create openrouter.ai account & generate API key Optional but highly recommended: deposit $10 Install…
My daily driver and one of the best investment since early 2025 until today! ๐…
My daily driver and one of the best investment since 2024 until today! ๐ โ …
Getting verified SSL information with Python (3.x) is very easy. Code examples for it are…
By default, Spring Data Couchbase implements single-bucket configuration. In this default implementation, all POJO (Plain…
Last year, Google released Firebase Auth Emulator as a new component in Firebase Emulator. In…