domino-server/src/server/db/mongo/NamespacesMongoManager.ts
2024-07-06 20:32:41 +02:00

77 lines
2.5 KiB
TypeScript

import { PipelineLibrary } from './common/PipelineLibrary';
import { mongoExecute } from './common/mongoDBPool';
import { BaseMongoManager } from './common/BaseMongoManager';
import { Namespace } from '../interfaces.js';
import { Document, ObjectId } from 'mongodb';
export class NamespacesMongoManager extends BaseMongoManager{
collection = 'namespaces';
constructor() {
super();
}
async createNamespace(namespace: Namespace): Promise<string> {
return await mongoExecute(async ({collection}) => {
const now = new Date().getTime();
delete namespace.users;
const result = await collection?.insertOne({
...namespace,
createdAt: now,
modifiedAt: now
});
return result?.insertedId.toString() || '';
}, {colName: this.collection})
}
async updateNamespace(id: string, namespace: Namespace): Promise<number> {
return await mongoExecute(async ({collection}) => {
const now = new Date().getTime();
const { name, description, type } = namespace;
const result = await collection?.updateOne({
_id: this.toObjectId(id),
}, {
$set: {
name,
description,
type,
modifiedAt: now
}
});
return result?.modifiedCount || 0;
}, {colName: this.collection})
}
async getNamespace(namespaceId: string): Promise<Document | null> {
const pipeline = PipelineLibrary.namespacesGetById(this.toObjectId((namespaceId)));
return await mongoExecute(async ({collection}) => {
const cursor: Document[] | undefined = await collection?.aggregate(pipeline).toArray();
if (cursor === undefined ||cursor.length === 0) {
return null;
}
return cursor[0];
}, {colName: this.collection})
}
async getDefaultNamespace(): Promise<Namespace> {
return await mongoExecute(async ({collection}) => {
return await collection?.findOne({
default: true
});
}, {colName: this.collection});
}
async getNamespaces(): Promise<Namespace[]> {
const pipeline = PipelineLibrary.namespacesGetNamespaces();
return await mongoExecute(async ({collection}) => {
return await collection?.aggregate(pipeline).toArray();
}, {colName: this.collection})
}
async deleteNamespace(_id: string): Promise<number> {
return await mongoExecute(async ({collection}) => {
const result = await collection?.deleteOne({ _id: this.toObjectId(_id) });
return result?.deletedCount || 0;
}, {colName: this.collection})
}
}