I think it's done?

This commit is contained in:
Daniel Ledda
2020-07-17 22:23:05 +02:00
parent 4542036b77
commit 42b7560d6d
21 changed files with 443 additions and 272 deletions

View File

@@ -1,6 +1,6 @@
import mongo from "mongodb";
import {tryQuery} from "./database";
import {MongoError} from "../errors";
import {tryQuery} from "../database";
import {InvalidIdError, MongoError} from "../errors";
import ActiveRecord, {ActiveRecordId} from "../Objects/ActiveRecord";
@@ -19,10 +19,15 @@ abstract class MongoStoredObjectCollection<IRawData extends {id: ActiveRecordId}
});
}
protected async mongoRead(id: string): Promise<IRawData | null> {
return tryQuery(async () =>
await this.mongoDbClientCollection.findOne({_id: id})
);
protected async mongoRead(id: string): Promise<IRawData> {
return tryQuery(async () => {
const result = await this.mongoDbClientCollection.findOne({_id: id});
if (result) {
return result;
} else {
throw new InvalidIdError(`Object in collection "${typeof this}" with id ${JSON.stringify(id)} not found!`);
}
});
}
protected async mongoFindByAttribute(attribute: string, value: any): Promise<IRawData | null> {
@@ -31,7 +36,7 @@ abstract class MongoStoredObjectCollection<IRawData extends {id: ActiveRecordId}
);
}
protected async mongoDelete(objectId: ActiveRecordId, returnObject?: boolean): Promise<IRawData | null | void> {
protected async mongoDelete(objectId: ActiveRecordId, returnObject?: boolean): Promise<IRawData | void> {
let deletedObject;
if (returnObject ?? true) {
deletedObject = await this.mongoRead(objectId);
@@ -40,15 +45,19 @@ abstract class MongoStoredObjectCollection<IRawData extends {id: ActiveRecordId}
if (deleteWriteOpResult.result.ok === 1) {
return deletedObject;
} else {
throw new MongoError(`Error deleting the object with id: ${JSON.stringify(objectId)}`);
throw new MongoError(`Error deleting the object in collection "${typeof this}" with id: ${JSON.stringify(objectId)}`);
}
}
protected async mongoSave(object: IRawData) {
protected async mongoUpdate(object: Partial<IRawData> & {id: ActiveRecordId}) {
await tryQuery(() =>
this.mongoDbClientCollection.findOneAndUpdate({_id: object.id}, {$set: {...object, id: undefined}})
);
}
protected idFromRecordOrId<T extends ActiveRecord>(recordOrRecordId: T | ActiveRecordId): ActiveRecordId {
return typeof recordOrRecordId === "string" ? recordOrRecordId : recordOrRecordId.getId();
}
}