Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(session): add POST delete-chat endpoint (#261)
Tobias Strebitzer01f8faabbda8
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 7c82c4878..1aa52bbfa 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -1158,6 +1158,17 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}}+ async deleteChat(chatId: string): Promise<boolean> {+ this.ensureReady();+ try {+ const chat = await this.client!.getChatById(chatId);+ return await chat.delete();+ } catch (error) {+ this.logger.error(`Error deleting chat ${chatId}`, String(error));+ return false;+ }+ }+async sendChatState(chatId: string, state: ChatState): Promise<void> {this.ensureReady();try {diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 16b035e6b..fbfa3853a 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -375,6 +375,7 @@ export interface IWhatsAppEngine {// ChatsgetChats(): Promise<ChatSummary[]>;sendSeen(chatId: string): Promise<boolean>;+ deleteChat(chatId: string): Promise<boolean>;/*** Send a typing/recording presence indicator to a chat, or clear it (`paused`).* Engine-agnostic and best-effort: engines without a presence concept should no-op.diff --git a/src/modules/session/dto/delete-chat.dto.ts b/src/modules/session/dto/delete-chat.dto.tsnew file mode 100644index 000000000..250ab7d78--- /dev/null+++ b/src/modules/session/dto/delete-chat.dto.ts@@ -0,0 +1,17 @@+import { ApiProperty } from '@nestjs/swagger';+import { IsNotEmpty, IsString, Matches } from 'class-validator';++export class DeleteChatDto {+ @ApiProperty({+ description: "Chat ID in the active engine's native format (e.g. [email protected] on whatsapp-web.js)",+ example: '[email protected]',+ })+ @IsString()+ @IsNotEmpty()+ // Engine-neutral structural check (localpart@host, no whitespace) so a different engine's JID scheme+ // (e.g. Baileys `…@s.whatsapp.net`) is accepted too; the adapter validates/normalises for its engine.+ @Matches(/^[^\s@]+@[^\s@]+$/, {+ message: 'chatId must be a valid chat JID in the form localpart@host',+ })+ chatId: string;+}diff --git a/src/modules/session/dto/index.ts b/src/modules/session/dto/index.tsindex 0b28b7c84..cd141f617 100644--- a/src/modules/session/dto/index.ts+++ b/src/modules/session/dto/index.ts@@ -1,5 +1,6 @@export * from './create-session.dto';export * from './session-response.dto';export * from './mark-chat-read.dto';+export * from './delete-chat.dto';export * from './send-chat-state.dto';export * from './request-pairing-code.dto';diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex a065241cc..062ac2e1e 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -6,6 +6,7 @@ import {SessionResponseDto,QRCodeResponseDto,MarkChatReadDto,+ DeleteChatDto,SendChatStateDto,RequestPairingCodeDto,PairingCodeResponseDto,@@ -213,6 +214,18 @@ export class SessionController {return { success };}+ @Post(':id/chats/delete')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Delete a chat from the chat list (e.g. a group you have left)' })+ @ApiParam({ name: 'id', description: 'Session ID' })+ @ApiResponse({ status: 200, description: 'Chat deleted successfully' })+ @ApiResponse({ status: 400, description: 'Session not ready' })+ @ApiResponse({ status: 404, description: 'Session not found' })+ async deleteChat(@Param('id') id: string, @Body() dto: DeleteChatDto): Promise<{ success: boolean }> {+ const success = await this.sessionService.deleteChat(id, dto.chatId);+ return { success };+ }+@Post(':id/chats/typing')@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: "Send a typing/recording presence indicator to a chat (or clear it with 'paused')" })diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex fa25192c1..1190a8028 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -77,6 +77,7 @@ describe('SessionService', () => {getGroups: jest.fn().mockResolvedValue([]),getChats: jest.fn().mockResolvedValue([]),sendSeen: jest.fn().mockResolvedValue(true),+ deleteChat: jest.fn().mockResolvedValue(true),sendChatState: jest.fn().mockResolvedValue(undefined),};@@ -677,6 +678,31 @@ describe('SessionService', () => {});});+ // ── deleteChat ────────────────────────────────────────────────────++ describe('deleteChat', () => {+ it('should delegate to engine.deleteChat with the chatId', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.start('sess-uuid-1');+ mockEngine.deleteChat.mockResolvedValue(true);++ const result = await service.deleteChat('sess-uuid-1', '[email protected]');++ expect(mockEngine.deleteChat).toHaveBeenCalledWith('[email protected]');+ expect(result).toBe(true);+ });++ it('should throw BadRequestException when session is not started', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);++ await expect(service.deleteChat('sess-uuid-1', '[email protected]')).rejects.toThrow(BadRequestException);+ });+ });+// ── sendChatState (typing/recording/paused) ───────────────────────describe('sendChatState', () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex b687bcc7e..8dfd5b980 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -805,6 +805,17 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn engine.sendSeen(chatId);}+ async deleteChat(id: string, chatId: string): Promise<boolean> {+ await this.findOne(id); // Verify session exists+ const engine = this.engines.get(id);++ if (!engine) {+ throw new BadRequestException('Session is not started');+ }++ return engine.deleteChat(chatId);+ }+async sendChatState(id: string, chatId: string, state: ChatState): Promise<void> {await this.findOne(id); // Verify session existsconst engine = this.engines.get(id);