Massive restructuring, most of the progress on reorganising Data Access Layer etc. finished. Gotta get the app back up and running now

This commit is contained in:
Daniel Ledda
2020-07-17 11:40:53 +02:00
parent cef6249c09
commit 4542036b77
33 changed files with 784 additions and 852 deletions

View File

@@ -0,0 +1,55 @@
import mongo from "mongodb";
import {tryQuery} from "./database";
import {MongoError} from "../errors";
import ActiveRecord, {ActiveRecordId} from "../Objects/ActiveRecord";
abstract class MongoStoredObjectCollection<IRawData extends {id: ActiveRecordId}> {
protected constructor(protected mongoDbClientCollection: mongo.Collection) {}
protected async mongoCreate(objectData: Omit<IRawData, "id">): Promise<IRawData> {
return tryQuery(async () => {
const insertOneWriteOpResult = await this.mongoDbClientCollection.insertOne(objectData);
if (insertOneWriteOpResult.result.ok === 1) {
return insertOneWriteOpResult.ops[0]
} else {
throw new MongoError(`Error creating the object: ${JSON.stringify(objectData)}`);
}
});
}
protected async mongoRead(id: string): Promise<IRawData | null> {
return tryQuery(async () =>
await this.mongoDbClientCollection.findOne({_id: id})
);
}
protected async mongoFindByAttribute(attribute: string, value: any): Promise<IRawData | null> {
return tryQuery(async () =>
await this.mongoDbClientCollection.findOne({[attribute]: value})
);
}
protected async mongoDelete(objectId: ActiveRecordId, returnObject?: boolean): Promise<IRawData | null | void> {
let deletedObject;
if (returnObject ?? true) {
deletedObject = await this.mongoRead(objectId);
}
const deleteWriteOpResult = await this.mongoDbClientCollection.deleteOne({_id: objectId});
if (deleteWriteOpResult.result.ok === 1) {
return deletedObject;
} else {
throw new MongoError(`Error deleting the object with id: ${JSON.stringify(objectId)}`);
}
}
protected async mongoSave(object: IRawData) {
await tryQuery(() =>
this.mongoDbClientCollection.findOneAndUpdate({_id: object.id}, {$set: {...object, id: undefined}})
);
}
}
export default MongoStoredObjectCollection;