Notes/src/entities/entity.js

55 lines
1.3 KiB
JavaScript
Raw Normal View History

"use strict";
const utils = require('../services/utils');
class Entity {
2018-08-22 23:37:06 +02:00
/**
* @param {object} [row] - database row representing given entity
*/
2018-04-01 11:42:12 -04:00
constructor(row = {}) {
for (const key in row) {
2019-02-08 21:01:26 +01:00
// ! is used when joint-fetching notes and note_contents objects for performance
if (!key.startsWith('!')) {
this[key] = row[key];
}
}
if ('isDeleted' in this) {
this.isDeleted = !!this.isDeleted;
}
}
2018-03-31 23:08:22 -04:00
2018-04-02 20:30:00 -04:00
beforeSaving() {
2018-08-27 23:04:52 +02:00
this.generateIdIfNecessary();
const origHash = this.hash;
this.hash = this.generateHash();
this.isChanged = origHash !== this.hash;
}
2018-08-27 23:04:52 +02:00
generateIdIfNecessary() {
if (!this[this.constructor.primaryKeyName]) {
this[this.constructor.primaryKeyName] = utils.newEntityId();
}
}
generateHash() {
let contentToHash = "";
2018-05-22 22:22:15 -04:00
for (const propertyName of this.constructor.hashedProperties) {
contentToHash += "|" + this[propertyName];
}
return utils.hash(contentToHash).substr(0, 10);
2018-04-02 20:30:00 -04:00
}
2018-03-31 23:08:22 -04:00
async save() {
await require('../services/repository').updateEntity(this);
2018-04-02 22:53:01 -04:00
return this;
2018-03-31 23:08:22 -04:00
}
}
module.exports = Entity;