diff --git a/packages/tom-server/src/active-contacts-api/services/index.ts b/packages/tom-server/src/active-contacts-api/services/index.ts index 5b3dd48f..78472e76 100644 --- a/packages/tom-server/src/active-contacts-api/services/index.ts +++ b/packages/tom-server/src/active-contacts-api/services/index.ts @@ -55,6 +55,23 @@ class ActiveContactsService implements IActiveContactsService { */ save = async (userId: string, contacts: string): Promise => { try { + const existing = await this.db.get( + 'activeContacts' as Collections, + ['contacts'], + { userId } + ) + + if (existing.length > 0) { + await this.db.update( + 'activeContacts' as Collections, + { contacts }, + 'userId', + userId + ) + this.logger.info('active contacts updated successfully') + return + } + await this.db.insert('activeContacts' as Collections, { userId, contacts diff --git a/packages/tom-server/src/active-contacts-api/tests/controllers.test.ts b/packages/tom-server/src/active-contacts-api/tests/controllers.test.ts index 9dce895a..d792706f 100644 --- a/packages/tom-server/src/active-contacts-api/tests/controllers.test.ts +++ b/packages/tom-server/src/active-contacts-api/tests/controllers.test.ts @@ -91,6 +91,7 @@ describe('the active contacts API controller', () => { describe('active contacts save', () => { it('should try to save active contacts', async () => { + dbMock.get.mockResolvedValue([]) dbMock.insert.mockResolvedValue([]) const response = await supertest(app) diff --git a/packages/tom-server/src/active-contacts-api/tests/service.test.ts b/packages/tom-server/src/active-contacts-api/tests/service.test.ts index 33741258..264b9265 100644 --- a/packages/tom-server/src/active-contacts-api/tests/service.test.ts +++ b/packages/tom-server/src/active-contacts-api/tests/service.test.ts @@ -6,7 +6,8 @@ describe('The active contacts service', () => { const dbMock = { get: jest.fn(), insert: jest.fn(), - deleteEqual: jest.fn() + deleteEqual: jest.fn(), + update: jest.fn() } const loggerMock = { @@ -22,6 +23,7 @@ describe('The active contacts service', () => { it('should save active contacts for a user', async () => { dbMock.insert.mockResolvedValue(undefined) + dbMock.get.mockResolvedValue([]) await expect( activeContactsService.save('test', 'contact') @@ -33,6 +35,22 @@ describe('The active contacts service', () => { }) }) + it('should update active contacts for a user if there are existing ones', async () => { + dbMock.get.mockResolvedValue([{ userId: 'test', contacts: 'test contact' }]) + dbMock.update.mockResolvedValue(undefined) + + await expect( + activeContactsService.save('test', 'contact') + ).resolves.not.toThrow() + + expect(dbMock.update).toHaveBeenCalledWith( + 'activeContacts', + { contacts: 'contact' }, + 'userId', + 'test' + ) + }) + it('should fetch active contacts for a user', async () => { dbMock.get.mockResolvedValue([{ userId: 'test', contacts: 'contact' }])