kannon/models/Base.js

106 lines
2.8 KiB
JavaScript
Raw Normal View History

2022-06-03 17:04:44 +02:00
class Base {
constructor() {
}
async save() {
if (!this.isValid()) {
return;
}
try {
const [element, created] = await (await this.getModel()).findOrCreate({
where: await this.#createWhereClause()
});
if (created) {
logger.debug('created \'' + this.tableName + '\' entry: ' + JSON.stringify(element));
}
if (element?.id === undefined) {
return undefined;
}
2022-06-15 16:56:38 +02:00
this.#fillThis(element);
2022-06-03 17:04:44 +02:00
} catch (error) {
logger.error('error finding or creating \'' + this.tableName + '\' entry: \'' + JSON.stringify(this) + '\' > ' + error);
}
}
async find() {
if (!this.isValid()) {
return;
}
try {
const element = await (await this.getModel()).findOne({
where: await this.#createWhereClause()
});
if (element?.id === undefined) {
return undefined;
}
this.#fillThis(element);
} catch (error) {
logger.error('error finding \'' + this.tableName + '\' entry: \'' + JSON.stringify(this) + '\' > ' + error);
}
}
async createTable() {
return await createTable();
}
async createTable() {
const model = await this.getModel();
if (model === undefined) {
return;
}
await model.sync({ alter: true });
}
async getModel() {
return undefined;
}
isValid() {
return false;
}
2022-06-15 16:56:38 +02:00
isRelationTable() {
return this.relationTable === true;
}
2022-06-03 17:04:44 +02:00
#fillThis(data) {
if (data === undefined || data.dataValues === undefined || data.dataValues.id === undefined || data.dataValues.id < 0) {
return;
}
for (const key in data.dataValues) {
this[key] = data.dataValues[key];
}
}
async #createWhereClause(fields) {
const model = await this.getModel();
if (model === undefined || model.tableAttributes === undefined) {
return undefined;
}
const where = {};
for (const key in model.tableAttributes) {
if (key === 'id' || key === 'createdAt' || key === 'updatedAt' || fields !== undefined && (key !== fields || !fields.includes(key))) {
continue;
}
const value = this[key];
if (value === undefined) {
continue;
}
2022-06-15 16:56:38 +02:00
if (this.isRelationTable()) {
const id = value.id;
if (id === undefined) {
continue;
}
where[key] = id;
} else {
where[key] = value;
}
2022-06-03 17:04:44 +02:00
}
return where;
}
}
module.exports = Base;