feat(wallet): migrate to backend API
This commit is contained in:
+56
-3
@@ -1,5 +1,58 @@
|
||||
import { useWalletStore } from "@/store/wallet"
|
||||
import type { WalletTransaction } from "@/lib/types"
|
||||
|
||||
export function listTransactions() {
|
||||
return useWalletStore.getState().transactions
|
||||
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 ?? 1000
|
||||
const searchParams = new URLSearchParams({
|
||||
offset: String(offset),
|
||||
limit: String(limit),
|
||||
})
|
||||
return `${path}?${searchParams.toString()}`
|
||||
}
|
||||
|
||||
function unwrapWalletBalance(value: unknown): number | undefined {
|
||||
if (typeof value === "number") return value
|
||||
if (typeof value !== "object" || value === null) return undefined
|
||||
|
||||
const v = value as { balance?: unknown; amount?: unknown }
|
||||
if (typeof v.balance === "number") return v.balance
|
||||
if (typeof v.amount === "number") return v.amount
|
||||
return undefined
|
||||
}
|
||||
|
||||
export async function getWalletBalance(): Promise<number> {
|
||||
const res = await httpJson<unknown>("/api/v1/wallet/balance", { cache: "no-store" })
|
||||
const balance = unwrapWalletBalance(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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user