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