@avonjs/avonjs
Version:
A fluent Node.js API generator.
54 lines (53 loc) • 1.66 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const luxon_1 = require("luxon");
exports.default = (Parent) => {
class HasTimestamps extends Parent {
/**
* Store given model into the storage.
*/
async store(model) {
//@ts-ignore
return super.store(this.fillTimestamps(model));
}
/**
* Update the given model in storage.
*/
async update(model) {
//@ts-ignore
return super.update(this.fillTimestamps(model, [this.getUpdatedAtKey()]));
}
/**
* Fill the timestamps for given attributes.
*/
fillTimestamps(model, attributes) {
const forcedToUpdate = Array.isArray(attributes) && attributes.length > 0;
(attributes ?? [this.getCreatedAtKey(), this.getUpdatedAtKey()]).forEach((attribute) => {
if (forcedToUpdate ||
[null, undefined].includes(model.getAttribute(attribute))) {
model.setAttribute(attribute, this.freshTimestamp());
}
});
return model;
}
/**
* Get name of `created_at` key.
*/
getCreatedAtKey() {
return 'created_at';
}
/**
* Get name of `update_at` key.
*/
getUpdatedAtKey() {
return 'updated_at';
}
/**
* Get a fresh timestamp for the model.
*/
freshTimestamp() {
return luxon_1.DateTime.now().toSQL({ includeOffset: false });
}
}
return HasTimestamps;
};