Skip to content

Commit

Permalink
chore: Count message stats only from distinct recipients
Browse files Browse the repository at this point in the history
  • Loading branch information
diego3g committed Aug 9, 2021
1 parent d782cd5 commit 4e1d1b4
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -64,32 +64,36 @@ export class InMemoryMessagesRepository implements IMessagesRepository {

async getMessageStats(messageId: string): Promise<MessageStats> {
const result = {
CLICK: 0,
DELIVER: 0,
OPEN: 0,
} as MessageStatsRaw
CLICK: new Set<string>(),
DELIVER: new Set<string>(),
OPEN: new Set<string>(),
}

this.items
.find(item => item.id === messageId)
.recipients.forEach(recipient => {
recipient.events.forEach(event => {
switch (event.type.value) {
case 'CLICK':
result.CLICK++
result.CLICK.add(recipient.id)
break
case 'DELIVER':
result.DELIVER++
result.DELIVER.add(recipient.id)
break
case 'OPEN':
result.OPEN++
result.OPEN.add(recipient.id)
break
default:
break
}
})
})

return MessageStatsMapper.toDto(result)
return MessageStatsMapper.toDto({
CLICK: result.CLICK.size,
DELIVER: result.DELIVER.size,
OPEN: result.OPEN.size,
})
}

async save(message: Message): Promise<void> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,20 @@ export class PrismaMessagesRepository implements IMessagesRepository {
}

async getMessageStats(messageId: string): Promise<MessageStats> {
const stats = await prisma.event.groupBy({
by: ['type'],
_count: true,
where: {
type: {
in: ['OPEN', 'CLICK', 'DELIVER'],
},
recipient: {
message_id: messageId,
},
},
})
const stats = await prisma.$queryRaw<
Array<{
type: keyof MessageStatsRaw
count: number
}>
>`
SELECT type, count(distinct events.recipient_id) FROM events
INNER JOIN recipients ON recipients.id = events.recipient_id
WHERE recipients.message_id = ${messageId}
GROUP BY events.type;
`

const statsParsed = stats.reduce((acc, item) => {
acc[item.type] = item._count
acc[item.type] = item.count

return acc
}, {}) as MessageStatsRaw
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ describe('Get Message Stats', () => {
recipientId: 'fake-recipient-id',
type: Type.create('CLICK').value as Type,
}).value as Event,
Event.create({
recipientId: 'fake-recipient-id',
type: Type.create('CLICK').value as Type,
}).value as Event,
],
}),
Recipient.create({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ describe('Get Message Stats (e2e)', () => {
id: uuid(),
type: 'CLICK',
},
{
id: uuid(),
type: 'CLICK',
},
],
},
},
Expand Down

0 comments on commit 4e1d1b4

Please sign in to comment.