Programming

Created and modified timestamps in LoopBack 4

A creation timestamp and a modification timestamp have different rules.

An API code card between two small clock dials and a narrow database cylinder

A creation timestamp and a modification timestamp have different rules. The first records when the record was created; the second changes when a successful write changes that record.

A default only solves creation#

LoopBack model properties can provide defaults, but a default value does not by itself implement every update path. Check the LoopBack 4 model documentation and the connector used by your application.

The original post reached through a model object with any and attached a persist observer. That is not a connector-independent recipe for a typed LoopBack 4 repository.

Put the write rule in one place#

Use the repository or service layer that owns the writes. Set both fields during creation, preserve the existing creation time on updates, and set the modification time at the successful write boundary. For example, this small helper expresses the update rule without claiming to be a complete repository implementation:

typescript
type Audit = {createdAt: string; modifiedAt: string};

function updatedAudit(existing: Audit, now: Date): Audit {
  return {...existing, modifiedAt: now.toISOString()};
}

Test all write paths#

Cover create, update-by-ID, replacement and bulk updates if your application exposes them. Test rejected writes too: a failed operation should not persist a newer modification time. If the database enforces timestamps, document that ownership instead of maintaining a competing application clock rule.