55 lines
2.0 KiB
TypeScript
55 lines
2.0 KiB
TypeScript
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; |