Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(template): answer 404 when creating a template for a missing session
Yudhi Armyndharis0557fdd28e33
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 4124dd93f..229b6dfef 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -3303,7 +3303,7 @@ Reject pending join requests. Same body, response shape, batch-guard contract an### 6.4.5 Message Templates-Reusable message templates scoped to a session, with `{{variable}}` placeholders rendered at send time. All routes are nested under `/api/sessions/:sessionId/templates` and require an **OPERATOR** key. The `sessionId` is stored on the template but is **not** validated against an existing session in these handlers.+Reusable message templates scoped to a session, with `{{variable}}` placeholders rendered at send time. All routes are nested under `/api/sessions/:sessionId/templates` and require an **OPERATOR** key. The `sessionId` is stored on the template; only `POST` checks that the session exists, the other handlers do not validate it.#### GET /api/sessions/:sessionId/templates@@ -3378,9 +3378,9 @@ Create a message template for the session (with `{{variable}}` placeholders in t**Path parameters**-| Name | Type | Description |-| --------- | ------ | ------------------------------------------------------------------------------------------------------ |-| sessionId | string | Session ID; stored as `template.sessionId`. Not validated against an existing session in this handler. |+| Name | Type | Description |+| --------- | ------ | ------------------------------------------------------------------------------------------- |+| sessionId | string | Session ID; stored as `template.sessionId`. Must name an existing session, otherwise `404`. |**Request body** — `CreateTemplateDto`@@ -3417,7 +3417,7 @@ Returns the saved `Template` entity raw (no envelope). The lazy `session` relati}```-**Errors:** `400` validation failure (missing/empty `name`/`body`, over-length, or any extra field rejected by `forbidNonWhitelisted`) · `401` missing/invalid `X-API-Key` · `403` key below OPERATOR role · `409` duplicate `name` for the session+**Errors:** `400` validation failure (missing/empty `name`/`body`, over-length, or any extra field rejected by `forbidNonWhitelisted`) · `401` missing/invalid `X-API-Key` · `403` key below OPERATOR role · `404` no session with that id (`{ "statusCode": 404, "message": "Session with id '<id>' not found", "error": "Not Found" }`) · `409` duplicate `name` for the session#### PUT /api/sessions/:sessionId/templates/:iddiff --git a/openapi.json b/openapi.jsonindex db4e827fd..e15d7aad9 100644--- a/openapi.json+++ b/openapi.json@@ -3892,6 +3892,9 @@}}},+ "404": {+ "description": "Session not found"+ },"409": {"description": "A template with that name already exists for the session"}diff --git a/src/modules/template/template.controller.ts b/src/modules/template/template.controller.tsindex 55e1ea788..db64d9b47 100644--- a/src/modules/template/template.controller.ts+++ b/src/modules/template/template.controller.ts@@ -16,6 +16,7 @@ export class TemplateController {@ApiOperation({ summary: 'Create a message template for the session' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiResponse({ status: 201, description: 'Template created', type: TemplateResponseDto })+ @ApiResponse({ status: 404, description: 'Session not found' })@ApiResponse({ status: 409, description: 'A template with that name already exists for the session' })async create(@Param('sessionId') sessionId: string, @Body() dto: CreateTemplateDto): Promise<Template> {return this.templateService.create(sessionId, dto);diff --git a/src/modules/template/template.module.ts b/src/modules/template/template.module.tsindex 9460ccb1a..7a836c9c5 100644--- a/src/modules/template/template.module.ts+++ b/src/modules/template/template.module.ts@@ -3,9 +3,10 @@ import { TypeOrmModule } from '@nestjs/typeorm';import { Template } from './entities/template.entity';import { TemplateService } from './template.service';import { TemplateController } from './template.controller';+import { Session } from '../session/entities/session.entity';@Module({- imports: [TypeOrmModule.forFeature([Template], 'data')],+ imports: [TypeOrmModule.forFeature([Template, Session], 'data')],controllers: [TemplateController],providers: [TemplateService],exports: [TemplateService],diff --git a/src/modules/template/template.service.spec.ts b/src/modules/template/template.service.spec.tsindex 8571ca183..4b8275bf5 100644--- a/src/modules/template/template.service.spec.ts+++ b/src/modules/template/template.service.spec.ts@@ -25,6 +25,7 @@ function createMockTemplate(overrides: Partial<Template> = {}): Template {describe('TemplateService', () => {let service: TemplateService;let repository: jest.Mocked<Partial<Repository<Template>>>;+ let sessionRepository: { exists: jest.Mock };beforeEach(async () => {repository = {@@ -35,8 +36,14 @@ describe('TemplateService', () => {remove: jest.fn().mockResolvedValue(undefined),};+ sessionRepository = { exists: jest.fn().mockResolvedValue(true) };+const module: TestingModule = await Test.createTestingModule({- providers: [TemplateService, { provide: getRepositoryToken(Template, 'data'), useValue: repository }],+ providers: [+ TemplateService,+ { provide: getRepositoryToken(Template, 'data'), useValue: repository },+ { provide: getRepositoryToken(Session, 'data'), useValue: sessionRepository },+ ],}).compile();service = module.get<TemplateService>(TemplateService);@@ -45,6 +52,16 @@ describe('TemplateService', () => {// ── create ────────────────────────────────────────────────────────describe('create', () => {+ it('rejects a session that does not exist with 404 before touching the templates table', async () => {+ sessionRepository.exists.mockResolvedValue(false);++ await expect(service.create('ghost', { name: 'n', body: 'b' })).rejects.toThrow(+ new NotFoundException("Session with id 'ghost' not found"),+ );+ expect(sessionRepository.exists).toHaveBeenCalledWith({ where: { id: 'ghost' } });+ expect(repository.save).not.toHaveBeenCalled();+ });+it('should create a template with normalized null header/footer', async () => {await service.create('sess-1', { name: 'welcome', body: 'Hi {{name}}' });diff --git a/src/modules/template/template.service.ts b/src/modules/template/template.service.tsindex 9f5dfdfec..85d72c3c0 100644--- a/src/modules/template/template.service.ts+++ b/src/modules/template/template.service.ts@@ -2,6 +2,7 @@ import { BadRequestException, ConflictException, Injectable, NotFoundException }import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { Template } from './entities/template.entity';+import { Session } from '../session/entities/session.entity';import { CreateTemplateDto, UpdateTemplateDto } from './dto';import { createLogger } from '../../common/services/logger.service';import { isUniqueViolation } from '../../common/utils/db-errors';@@ -13,9 +14,16 @@ export class TemplateService {constructor(@InjectRepository(Template, 'data')private readonly templateRepository: Repository<Template>,+ @InjectRepository(Session, 'data')+ private readonly sessionRepository: Repository<Session>,) {}async create(sessionId: string, dto: CreateTemplateDto): Promise<Template> {+ // The templates.sessionId FK turns a missing session into a driver error (500) at save time;+ // check first so the caller gets a truthful 404.+ if (!(await this.sessionRepository.exists({ where: { id: sessionId } }))) {+ throw new NotFoundException(`Session with id '${sessionId}' not found`);+ }const template = this.templateRepository.create({sessionId,name: dto.name,