Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(template): update only the supplied fields
Yudhi Armyndharisb36d6eb96a95
diff --git a/src/modules/template/template-concurrency.spec.ts b/src/modules/template/template-concurrency.spec.tsnew file mode 100644index 000000000..e359f2a7c--- /dev/null+++ b/src/modules/template/template-concurrency.spec.ts@@ -0,0 +1,92 @@+import 'reflect-metadata';+import { DataSource, Repository } from 'typeorm';+import { TemplateService } from './template.service';+import { Template } from './entities/template.entity';+import { Session, SessionStatus } from '../session/entities/session.entity';+import { UpdateTemplateDto } from './dto';++const deferred = () => {+ let resolve!: () => void;+ const promise = new Promise<void>(done => {+ resolve = done;+ });+ return { promise, resolve };+};++describe('concurrent template edits', () => {+ let database: DataSource;+ let repository: Repository<Template>;+ let service: TemplateService;+ let id: string;++ beforeEach(async () => {+ database = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [Session, Template],+ synchronize: true,+ logging: false,+ });+ await database.initialize();+ const sessions = database.getRepository(Session);+ await sessions.save(+ sessions.create({ id: 'session-a', name: 'session-a', status: SessionStatus.READY, config: {} }),+ { transaction: false },+ );+ repository = database.getRepository(Template);+ service = new TemplateService(repository, sessions);+ id = (await service.create('session-a', { name: 'greeting', body: 'old-body', footer: 'old-footer' })).id;+ });++ afterEach(async () => {+ jest.restoreAllMocks();+ if (database?.isInitialized) await database.destroy();+ });++ const stallRead = () => {+ const entered = deferred();+ const release = deferred();+ const real = repository.findOne.bind(repository);+ jest.spyOn(repository, 'findOne').mockImplementationOnce(async options => {+ const row = await real(options);+ entered.resolve();+ await release.promise;+ return row;+ });+ return { entered: entered.promise, release: release.resolve };+ };++ it.each<[UpdateTemplateDto, UpdateTemplateDto, Partial<Template>]>([+ [{ body: 'new-body' }, { footer: 'new-footer' }, { body: 'new-body', footer: 'new-footer' }],+ [{ name: 'renamed' }, { body: 'new-body' }, { name: 'renamed', body: 'new-body' }],+ [{}, { body: 'new-body' }, { name: 'greeting', body: 'new-body' }],+ ])('preserves independently supplied fields: %j / %j', async (slowPatch, fastPatch, expected) => {+ const gate = stallRead();+ const slow = service.update('session-a', id, slowPatch);+ try {+ await gate.entered;+ await service.update('session-a', id, fastPatch);+ } finally {+ gate.release();+ }+ await slow;+ expect(await repository.findOneByOrFail({ id })).toMatchObject(expected);+ });++ it('returns404 rather than reinserting a template deleted during the edit', async () => {+ const gate = stallRead();+ const slow = service.update('session-a', id, { body: 'late-body' });+ const outcome = slow.then(+ () => undefined,+ error => error as { status: number },+ );+ try {+ await gate.entered;+ await service.delete('session-a', id);+ } finally {+ gate.release();+ }+ expect(await outcome).toMatchObject({ status: 404 });+ expect(await repository.countBy({ id })).toBe(0);+ });+});diff --git a/src/modules/template/template.service.spec.ts b/src/modules/template/template.service.spec.tsindex 84584b563..565accf40 100644--- a/src/modules/template/template.service.spec.ts+++ b/src/modules/template/template.service.spec.ts@@ -34,6 +34,7 @@ describe('TemplateService', () => {create: jest.fn().mockImplementation((data: Partial<Template>) => ({ id: 'tpl-uuid-1', ...data }) as Template),save: jest.fn().mockImplementation((tpl: Template) => Promise.resolve(tpl)),remove: jest.fn().mockResolvedValue(undefined),+ update: jest.fn().mockResolvedValue({ affected: 1 }),};sessionRepository = { exists: jest.fn().mockResolvedValue(true) };@@ -188,10 +189,11 @@ describe('TemplateService', () => {await service.update('sess-1', 'tpl-uuid-1', { body: 'Updated body' });- expect(repository.save).toHaveBeenCalledWith(- expect.objectContaining({ body: 'Updated body', name: template.name }),- { transaction: false },+ expect(repository.update).toHaveBeenCalledWith(+ { id: 'tpl-uuid-1', sessionId: 'sess-1' },+ { body: 'Updated body' },);+ expect(repository.save).not.toHaveBeenCalled();});it('should throw NotFoundException for an unknown template', async () => {@@ -235,7 +237,7 @@ describe('TemplateService', () => {it('translates a duplicate-name violation on update into 409 Conflict', async () => {(repository.findOne as jest.Mock).mockResolvedValue(createMockTemplate());- (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation());+ (repository.update as jest.Mock).mockRejectedValueOnce(uniqueViolation());await expect(service.update('sess-1', 'tpl-uuid-1', { name: 'dup' })).rejects.toThrow(ConflictException);});diff --git a/src/modules/template/template.service.ts b/src/modules/template/template.service.tsindex 2e976900b..15830c046 100644--- a/src/modules/template/template.service.ts+++ b/src/modules/template/template.service.ts@@ -98,18 +98,21 @@ export class TemplateService {async update(sessionId: string, id: string, dto: UpdateTemplateDto): Promise<Template> {const template = await this.findOne(sessionId, id);- if (dto.name !== undefined) template.name = dto.name;- if (dto.body !== undefined) template.body = dto.body;- if (dto.header !== undefined) template.header = dto.header;- if (dto.footer !== undefined) template.footer = dto.footer;+ const patch: Partial<Pick<Template, 'name' | 'body' | 'header' | 'footer'>> = {};+ if (dto.name !== undefined) patch.name = dto.name;+ if (dto.body !== undefined) patch.body = dto.body;+ if (dto.header !== undefined) patch.header = dto.header;+ if (dto.footer !== undefined) patch.footer = dto.footer;+ if (Object.keys(patch).length === 0) return template;try {- // No transaction of its own: on SQLite's single shared connection the rollback of the unique- // violation handled below would also discard what other callers wrote while it was open.- return await this.templateRepository.save(template, { transaction: false });+ // Update only supplied fields, and never reinsert a concurrently deleted template.+ const result = await this.templateRepository.update({ id, sessionId }, patch);+ if (!result.affected) throw new NotFoundException(`Template with id '${id}' not found`);+ return await this.findOne(sessionId, id);} catch (err) {if (isUniqueViolation(err)) {- throw new ConflictException(`A template named '${template.name}' already exists for this session`);+ throw new ConflictException(`A template named '${dto.name ?? template.name}' already exists for this session`);}throw err;}