node-rigorous
Version:
Rigorous Framework
150 lines (107 loc) • 3.89 kB
JavaScript
module.exports = class CrudService {
constructor(model) {
this.model = model;
}
/**
* postXXX are meant to be override only contain operation that will not make
* CYCLE DEPENDENCY... So Be carefull
* Exemple: .remove function
*/
async postCreateIt(object = null) {
// empty
}
async postDeleteIt(resultArrayId = []) {
// empty
}
async postWriteIt(resultArray = []) {
// empty
}
async addDynamicFields(objects = []) {
return objects;
}
async createIt(attributesToBeDefined, params) {
try {
const object = await this.model.crudFunction.createObject(attributesToBeDefined, params);
await this.postCreateIt(object);
await this.postWriteIt([object]);
return object;
} catch (err) {
throw err;
}
}
async updateIt(queryRead, jsonFieldsUpdated, params) {
try {
let result = await this.model.crudFunction.updateObject(queryRead, jsonFieldsUpdated, params);
if (Array.isArray(result)) {
result = await this.addDynamicFields(result);
await this.postWriteIt(result);
} else {
result = (await this.addDynamicFields([result]))[0]; // eslint-disable-line prefer-destructuring
await this.postWriteIt([result]);
}
return result;
} catch (err) {
throw err;
}
}
async deleteIt(queryDelete) {
try {
const resultOneOrArrayId = await this.model.crudFunction.deleteObject(queryDelete);
if (Array.isArray(resultOneOrArrayId)) {
await this.postDeleteIt(resultOneOrArrayId);
} else {
await this.postDeleteIt([resultOneOrArrayId]);
}
return;
} catch (err) {
throw err;
}
}
async readIt(queryRead, params) {
try {
let result = await this.model.crudFunction.readObject(queryRead, params);
result = (await this.addDynamicFields([result]))[0]; // eslint-disable-line prefer-destructuring
return result;
} catch (err) {
throw err;
}
}
async readMany(queryRead, lastPaginateId, reverse, params) {
try {
let result = await this.model.crudFunction.readManyObject(queryRead, lastPaginateId, reverse, params);
result = await this.addDynamicFields(result);
return result;
} catch (err) {
throw err;
}
}
async readOrCreateIt(queryRead, attributesToBeDefinedIfCreation, params) {
try {
let object = await this.readIt(queryRead, params);
if (!object) {
object = await this.createIt(attributesToBeDefinedIfCreation, params);
}
return object;
} catch (err) {
throw err;
}
}
// We do not do upsert because we want to keep the logic process behing updateObject && createObject
async updateOrCreateIt(queryRead, jsonFieldsUpdated, attributesToBeDefinedIfCreation, params) {
let object = null;
try {
try {
object = await this.updateIt(queryRead, jsonFieldsUpdated, params);
} catch (err) {
if (err.response && err.response === errorTypes.DataNotFoundError) {
object = await this.createIt(attributesToBeDefinedIfCreation, params);
} else {
throw err;
}
}
return object;
} catch (err) {
throw err;
}
}
};