Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions services/addressService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,15 @@ export async function fetchAddressBySubstring (substring: string, includeTransac
}

export async function addressExists (addressString: string, raise = false): Promise<boolean> {
try {
await prisma.address.findUniqueOrThrow({
where: {
address: addressString
}
})
} catch (err: any) {
const address = await prisma.address.findUnique({
where: {
address: addressString
},
select: {
id: true
}
})
if (address === null) {
if (raise) {
throw new Error(RESPONSE_MESSAGES.NO_ADDRESS_FOUND_404.message)
}
Expand Down
34 changes: 34 additions & 0 deletions tests/unittests/addressService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,37 @@ describe('Create by substring', () => {
expect(result).toEqual(mockedBCHAddress)
})
})

describe('addressExists', () => {
it('returns true when the address exists', async () => {
prismaMock.address.findUnique.mockResolvedValue({ id: mockedBCHAddress.id } as any)
prisma.address.findUnique = prismaMock.address.findUnique

await expect(addressService.addressExists(mockedBCHAddress.address)).resolves.toBe(true)
})

it('returns false when the address is missing', async () => {
prismaMock.address.findUnique.mockResolvedValue(null)
prisma.address.findUnique = prismaMock.address.findUnique

await expect(addressService.addressExists(mockedBCHAddress.address)).resolves.toBe(false)
})

it('throws NO_ADDRESS_FOUND when raise is true and the address is missing', async () => {
prismaMock.address.findUnique.mockResolvedValue(null)
prisma.address.findUnique = prismaMock.address.findUnique

await expect(addressService.addressExists(mockedBCHAddress.address, true)).rejects.toThrow(
RESPONSE_MESSAGES.NO_ADDRESS_FOUND_404.message
)
})

it('propagates database errors instead of treating them as missing addresses', async () => {
const poolTimeout = new Error('Timed out fetching a new connection from the connection pool.')
prismaMock.address.findUnique.mockRejectedValue(poolTimeout)
prisma.address.findUnique = prismaMock.address.findUnique

await expect(addressService.addressExists(mockedBCHAddress.address, true)).rejects.toThrow(poolTimeout)
await expect(addressService.addressExists(mockedBCHAddress.address)).rejects.toThrow(poolTimeout)
})
})
Loading