1import { GraphQLClient } from 'graphql-request';
2
3import * as DevLauncherAuth from './native-modules/DevLauncherAuth';
4
5const useStaging = __DEV__;
6
7export const apiEndpoint = useStaging
8  ? `https://staging.exp.host/--/graphql`
9  : `https://exp.host/--/graphql`;
10export const websiteOrigin = useStaging ? `https://staging.expo.dev` : 'https://expo.dev';
11export const restEndpoint = useStaging
12  ? `https://staging.exp.host/--/api/v2`
13  : `https://exp.host/--/api/v2`;
14
15export const apiClient = new GraphQLClient(apiEndpoint);
16
17const headers = {
18  'content-type': 'application/json',
19};
20
21export async function restClient<T = any>(endpoint: string, options: RequestInit = {}) {
22  const config = {
23    method: options.body ? 'POST' : 'GET',
24    ...options,
25    headers: {
26      ...headers,
27      ...options.headers,
28    },
29  };
30
31  if (options.body != null) {
32    // @ts-ignore
33    config.body = JSON.stringify(body);
34  }
35
36  const url = `${restEndpoint}${endpoint}`;
37
38  const response = await fetch(url, config);
39
40  if (response.ok) {
41    return (await response.json()) as T;
42  } else {
43    const errorMessage = await response.text();
44    return Promise.reject(new Error(errorMessage));
45  }
46}
47
48export async function restClientWithTimeout<T = any>(
49  endpoint: string,
50  timeout: number,
51  options: RequestInit = {}
52) {
53  const controller = new AbortController();
54  const id = setTimeout(() => controller.abort(), timeout);
55  try {
56    return await restClient<T>(endpoint, {
57      ...options,
58      signal: controller.signal,
59    });
60  } finally {
61    clearTimeout(id);
62  }
63}
64
65export async function setSessionAsync(session: string | null) {
66  await DevLauncherAuth.setSessionAsync(session);
67  apiClient.setHeader('expo-session', session);
68  headers['expo-session'] = session;
69}
70