summaryrefslogtreecommitdiff
path: root/frontend/lib/api.ts
blob: 2c65ef23871a7e2b99fbd1aaeb7f5f89d4ea896e (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
59
60
61
62
63
64
65
66
67
import type { FinancialsResponse, HistoryPoint, MarketIndex, RatiosResponse, SearchResult, TickerOverview, ValuationResponse, WatchlistResponse } from "@/types/api";

const API_BASE = (process.env.NEXT_PUBLIC_API_BASE_URL || "").trim().replace(/\/$/, "");

export class ApiError extends Error {
  status: number;

  constructor(message: string, status: number) {
    super(message);
    this.name = "ApiError";
    this.status = status;
  }
}

async function request<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    ...init,
    headers: {
      "Content-Type": "application/json",
      ...(init?.headers || {})
    }
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    throw new ApiError(body.detail || `Request failed: ${res.status}`, res.status);
  }
  return res.json() as Promise<T>;
}

export const api = {
  search(query: string) {
    return request<SearchResult[]>(`/api/search?q=${encodeURIComponent(query)}`);
  },
  marketIndices() {
    return request<MarketIndex[]>("/api/market/indices");
  },
  overview(symbol: string) {
    return request<TickerOverview>(`/api/tickers/${encodeURIComponent(symbol)}/overview`);
  },
  history(symbol: string, period: string) {
    return request<HistoryPoint[]>(`/api/tickers/${encodeURIComponent(symbol)}/history?period=${encodeURIComponent(period)}`);
  },
  watchlist() {
    return request<WatchlistResponse>("/api/watchlist");
  },
  addWatchlist(symbol: string) {
    return request<WatchlistResponse>(`/api/watchlist/${encodeURIComponent(symbol)}`, { method: "POST" });
  },
  removeWatchlist(symbol: string) {
    return request<WatchlistResponse>(`/api/watchlist/${encodeURIComponent(symbol)}`, { method: "DELETE" });
  },
  financials(symbol: string, period: "annual" | "quarterly" = "annual") {
    return request<FinancialsResponse>(
      `/api/tickers/${encodeURIComponent(symbol)}/financials?period=${encodeURIComponent(period)}`
    );
  },
  valuation(symbol: string) {
    return request<ValuationResponse>(
      `/api/tickers/${encodeURIComponent(symbol)}/valuation`
    );
  },
  ratios(symbol: string) {
    return request<RatiosResponse>(
      `/api/tickers/${encodeURIComponent(symbol)}/ratios`
    );
  }
};