Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

src/vault: Include campaign data and sum of succeeded withdraws to vault's response #584

Merged
merged 3 commits into from
Dec 14, 2023
Merged
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
35 changes: 33 additions & 2 deletions apps/api/src/vault/vault.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ import { PrismaService } from '../prisma/prisma.service'
import { CreateVaultDto } from './dto/create-vault.dto'
import { UpdateVaultDto } from './dto/update-vault.dto'

type VaultWithWithdrawalSum = Prisma.VaultGetPayload<{
include: { campaign: { select: { id: true; title: true } } }
}> & {
withdrawnAmount: number
}

@Injectable()
export class VaultService {
constructor(
Expand All @@ -25,8 +31,33 @@ export class VaultService {
return await this.prisma.vault.create({ data: createVaultDto.toEntity() })
}

async findAll(): Promise<Vault[]> {
return await this.prisma.vault.findMany()
async findAll(): Promise<VaultWithWithdrawalSum[]> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow! That is some SQL magic!

const result = await this.prisma.$queryRaw<VaultWithWithdrawalSum[]>`
SELECT
v.id,
v.campaign_id as "campaignId",
v.created_at as "createdAt",
v.updated_at as "updatedAt",
v.currency, v."blockedAmount",
v.name,
v.amount,
json_build_object('id', campaign.id, 'title', campaign.title) AS campaign,
COALESCE(SUM(w."successfullWithdrawn")::INTEGER, 0) as "withdrawnAmount"
FROM vaults v
LEFT JOIN LATERAL (
SELECT SUM(amount)::INTEGER as "successfullWithdrawn"
FROM withdrawals
WHERE status::text = 'succeeded' AND source_vault_id::uuid = v.id::uuid
)as w
ON TRUE

LEFT JOIN LATERAL (
SELECT id, title FROM campaigns WHERE id::uuid = v.campaign_id::uuid
) as campaign ON TRUE

GROUP BY v.id, campaign.id, campaign.title
`
return result
}

async findByCampaignId(campaignId: string): Promise<Vault[]> {
Expand Down
Loading