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 async function setSessionAsync(session: string | null) {
49  await DevLauncherAuth.setSessionAsync(session);
50  apiClient.setHeader('expo-session', session);
51  headers['expo-session'] = session;
52}
53