summaryrefslogtreecommitdiff
path: root/gui/src/ajax/backend.ts
blob: 90a7ea57aafe711e4adcd03afef49171ee0bb27f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { BalanceMap, newCategoryBalanceMapFromDto } from "../types/balanceMap";
import { BudgetMap, newBudgetMapFromDto } from "../types/budgetMap";
import { Category, newCategoryFromDto } from "../types/category";

const backendUrl = "http://localhost:8000";

function makeGetter<T>(params: FetcherMakerParams<T>): Getter<T> {
  const parser =
    "parser" in params
      ? params.parser
      : (dto: unknown[]) => <T>dto.map(params.elementParser);

  return async function () {
    const response = await fetch(`${backendUrl}${params.path}`);
    const dto = await response.json();

    try {
      return parser(dto);
    } catch (err) {
      console.error(`Error parsing DTO. ${err?.toString() ?? ""}`);
      return null;
    }
  };
}

export const getAllCategories: Getter<Category[]> = async () => {
  const balances = await getAllCategoryBalances();
  const budgets = await getAllCurrentCategoryBudgets();
  return makeGetter<Category[]>({
    path: "/category",
    elementParser: newCategoryFromDto(balances, budgets),
  })();
};

export const getAllCategoryBalances: Getter<BalanceMap<Category>> = makeGetter<
  BalanceMap<Category>
>({
  path: "/balance/category",
  parser: newCategoryBalanceMapFromDto,
});

export const getAllCurrentCategoryBudgets: Getter<BudgetMap<Category>> =
  makeGetter<BudgetMap<Category>>({
    path: "/budget/category?current",
    parser: newBudgetMapFromDto,
  });

type FetcherMakerParams<T> = {
  path: string;
} & AnyParser<T>;

type Parser<T> = { parser: (dto: unknown) => T | null };
type ElementParser<T> = { elementParser: (dto: unknown) => T | null };
type AnyParser<T> = T extends any[]
  ? Parser<T> | ElementParser<T[number]>
  : Parser<T>;

type Getter<T> = () => Promise<T | null>;