Files
juwan-frontend/lib/api/transactions.ts
T

62 lines
1.5 KiB
TypeScript

import type { WalletTransaction } from "@/lib/types"
import { httpJson } from "./http"
type Paginated<T> = {
items: T[]
meta: {
total: number
offset: number
limit: number
}
}
export type ListWalletTransactionsOptions = {
offset?: number
limit?: number
}
function withOffsetLimit(path: string, options?: ListWalletTransactionsOptions): string {
const offset = options?.offset ?? 0
const limit = options?.limit ?? 100
const searchParams = new URLSearchParams({
offset: String(offset),
limit: String(limit),
})
return `${path}?${searchParams.toString()}`
}
type WalletBalanceResponse = {
balance: string
frozenBalance?: string
}
function parseBalance(value: unknown): number | undefined {
if (typeof value !== "object" || value === null) return undefined
const v = value as WalletBalanceResponse
if (typeof v.balance === "string") return Number(v.balance)
if (typeof v.balance === "number") return v.balance
return undefined
}
export async function getWalletBalance(): Promise<number> {
const res = await httpJson<unknown>("/api/v1/wallet/balance", { cache: "no-store" })
const balance = parseBalance(res)
if (balance === undefined) {
throw new Error("Invalid wallet balance response")
}
return balance
}
export async function listWalletTransactions(
options?: ListWalletTransactionsOptions,
): Promise<WalletTransaction[]> {
const res = await httpJson<Paginated<WalletTransaction>>(
withOffsetLimit("/api/v1/wallet/transactions", options),
{
cache: "no-store",
},
)
return res.items
}