File size: 1,823 Bytes
78d4e18
312fdff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78d4e18
312fdff
78d4e18
312fdff
 
 
 
78d4e18
312fdff
 
 
 
 
 
78d4e18
312fdff
 
 
 
 
 
78d4e18
312fdff
 
 
 
 
 
 
 
 
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
import { apiUrl, getSelectedStoreId } from '../config';
import {
  normalizeAnomalies,
  normalizeFunnel,
  normalizeHeatmap,
  normalizeMetrics,
} from './normalize';
import type {
  HealthResponse,
  StoreAnomalies,
  StoreFunnel,
  StoreHeatmap,
  StoreMetrics,
} from '../types/api';

async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(apiUrl(path), {
    ...init,
    headers: {
      Accept: 'application/json',
      ...init?.headers,
    },
  });

  if (!res.ok) {
    const body = await res.text().catch(() => '');
    throw new Error(
      `API ${res.status} ${res.statusText}${body ? `: ${body.slice(0, 200)}` : ''}`,
    );
  }

  return res.json() as Promise<T>;
}

export async function getStoreMetrics(storeId = getSelectedStoreId()): Promise<StoreMetrics> {
  const raw = await fetchJson<Record<string, unknown>>(
        `/stores/${encodeURIComponent(storeId)}/metrics`,
  );
  return normalizeMetrics(raw);
}

export async function getStoreFunnel(storeId = getSelectedStoreId()): Promise<StoreFunnel> {
  const raw = await fetchJson<Record<string, unknown>>(
    `/stores/${encodeURIComponent(storeId)}/funnel`,
  );
  return normalizeFunnel(raw);
}

export async function getStoreHeatmap(storeId = getSelectedStoreId()): Promise<StoreHeatmap> {
  const raw = await fetchJson<Record<string, unknown>>(
    `/stores/${encodeURIComponent(storeId)}/heatmap`,
  );
  return normalizeHeatmap(raw);
}

export async function getStoreAnomalies(storeId = getSelectedStoreId()): Promise<StoreAnomalies> {
  const raw = await fetchJson<Record<string, unknown>>(
    `/stores/${encodeURIComponent(storeId)}/anomalies`,
  );
  return normalizeAnomalies(raw);
}

export function getHealth(): Promise<HealthResponse> {
  return fetchJson<HealthResponse>('/health');
}