From fc2f43755695070e4dd2a8a62d5b8465cc981f48 Mon Sep 17 00:00:00 2001 From: Mathis Date: Mon, 14 Oct 2024 14:43:50 +0200 Subject: [PATCH] Implement group deletion and add group files retrieval Added logic to delete a group and update the associated files to have a null group reference. Also implemented a method to retrieve files associated with a group using pagination and search functionality. --- apps/backend/src/app/groups/groups.service.ts | 50 ++++++++++++++++--- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/apps/backend/src/app/groups/groups.service.ts b/apps/backend/src/app/groups/groups.service.ts index 6cfc453..c4d0c9d 100644 --- a/apps/backend/src/app/groups/groups.service.ts +++ b/apps/backend/src/app/groups/groups.service.ts @@ -1,13 +1,12 @@ -import { Injectable } from "@nestjs/common"; +import { Injectable, InternalServerErrorException, NotFoundException } from '@nestjs/common'; import { DbService } from "apps/backend/src/app/db/db.service"; -import { FilesGroupTable } from "apps/backend/src/app/db/schema"; -import { ilike } from "drizzle-orm"; +import { FilesGroupTable, FilesTable } from 'apps/backend/src/app/db/schema'; +import { and, eq, ilike } from 'drizzle-orm'; @Injectable() export class GroupsService { constructor(private readonly database: DbService) {} - //TODO a method to fetch groups in the database by a specific search with limit, offset and a search field (can be blank) async getGroupsByName(limit: number, offset: number, search: string) { return await this.database .use() @@ -34,13 +33,48 @@ export class GroupsService { } //TODO a method to delete a group and place the associated file at a null group reference - async deleteGroup(groupId: string) {} - - //TODO a method to get the files of a group in the database by a specific search with limit, offset and a search field (can be blank) + async deleteGroup(groupId: string) { + const groupInDb = await this.database.use() + .select() + .from(FilesGroupTable) + .where(eq(FilesGroupTable.uuid, groupId)) + .prepare("findGroupById") + .execute(); + if (groupInDb.length === 0) throw new NotFoundException("Group not found"); + // Replace entry by null + await this.database + .use() + .update(FilesTable) + // @ts-ignore + .set({ groupId: null }) + .where(eq(FilesTable.groupId, groupId)) + .prepare("updateFilesGroupReference") + .execute(); + try { + await this.database + .use() + .delete(FilesGroupTable) + .where(eq(FilesGroupTable.uuid, groupId)) + return true + } catch (e) { + throw new InternalServerErrorException("Error while deleting group"); + } + } + async findFilesForGroup( limit: number, offset: number, searchField: string, groupId: string, - ) {} + ) { + return await this.database + .use() + .select() + .from(FilesTable) + .where(and(eq(FilesTable.groupId, groupId), ilike(FilesTable.fileName, String(`%${searchField}%`)) ) ) + .limit(limit) + .offset(offset) + .prepare('findFilesInGroup') + .execute(); + } }