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