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 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  return fetch(url, config).then(async (response) => {
39    if (response.ok) {
40      return (await response.json()) as T;
41    } else {
42      const errorMessage = await response.text();
43      return Promise.reject(new Error(errorMessage));
44    }
45  });
46}
47
48export 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  return restClient<T>(endpoint, {
56    ...options,
57    signal: controller.signal,
58  }).finally(() => clearTimeout(id));
59}
60
61export async function setSessionAsync(session: string | null) {
62  await DevLauncherAuth.setSessionAsync(session);
63  apiClient.setHeader('expo-session', session);
64  headers['expo-session'] = session;
65}
66