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(); + } }