useTransactions.ts raw

   1  import useSWR, { SWRConfiguration } from "swr";
   2  
   3  import { ListTransactionsResponse } from "src/types";
   4  import { swrFetcher } from "src/utils/swr";
   5  
   6  const pollConfiguration: SWRConfiguration = {
   7    refreshInterval: 10000,
   8  };
   9  
  10  export type TransactionFilters = {
  11    searchTerm?: string;
  12    type?: "incoming" | "outgoing";
  13    minAmountSat?: number;
  14    hideFailed?: boolean;
  15  };
  16  
  17  export const defaultTransactionFilters: TransactionFilters = {};
  18  
  19  export function hasActiveTransactionFilters(filters: TransactionFilters) {
  20    return (
  21      !!filters.searchTerm ||
  22      !!filters.type ||
  23      (filters.minAmountSat ?? 0) > 0 ||
  24      !!filters.hideFailed
  25    );
  26  }
  27  
  28  export function getTransactionsUrl(
  29    appId?: number,
  30    limit = 100,
  31    page = 1,
  32    filters?: TransactionFilters
  33  ) {
  34    const offset = (page - 1) * limit;
  35    const searchParams = new URLSearchParams({
  36      limit: String(limit),
  37      offset: String(offset),
  38    });
  39  
  40    if (appId) {
  41      searchParams.set("appId", String(appId));
  42    }
  43    if (filters?.searchTerm) {
  44      searchParams.set("search", filters.searchTerm);
  45    }
  46    if (filters?.type) {
  47      searchParams.set("type", filters.type);
  48    }
  49    if (filters?.minAmountSat && filters.minAmountSat > 0) {
  50      searchParams.set("minAmountSat", String(filters.minAmountSat));
  51    }
  52    if (filters?.hideFailed) {
  53      searchParams.set("hideFailed", "true");
  54    }
  55  
  56    const url = `/api/transactions?${searchParams.toString()}`;
  57  
  58    return url;
  59  }
  60  
  61  export function useTransactions(
  62    appId?: number,
  63    poll = false,
  64    limit = 100,
  65    page = 1,
  66    filters?: TransactionFilters
  67  ) {
  68    const url = getTransactionsUrl(appId, limit, page, filters);
  69  
  70    return useSWR<ListTransactionsResponse>(
  71      url,
  72      swrFetcher,
  73      poll ? pollConfiguration : undefined
  74    );
  75  }
  76