forked from kriasoft/react-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrelay.ts
More file actions
38 lines (32 loc) · 1.14 KB
/
relay.ts
File metadata and controls
38 lines (32 loc) · 1.14 KB
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
/* SPDX-FileCopyrightText: 2014-present Kriasoft <hello@kriasoft.com> */
/* SPDX-License-Identifier: MIT */
import { Environment, Network, RecordSource, Store } from "relay-runtime";
import { config as appConfig } from ".";
type Config = {
baseUrl?: string;
request?: Request;
records?: ConstructorParameters<typeof RecordSource>[0];
};
/* eslint-disable @typescript-eslint/no-explicit-any */
export function createRelay(config: Config = {}): Environment {
const recordSource = new RecordSource(config.records);
const store = new Store(recordSource);
const baseUrl = config.baseUrl || "";
const network = Network.create((operation, variables): Promise<any> => {
const cookie = config.request?.headers.get("cookie");
return fetch(`${baseUrl}${appConfig.api.path}`, {
method: "POST",
headers: {
...(cookie && { cookie }),
"content-Type": "application/json",
},
body: JSON.stringify({ query: operation.text, variables }),
...(!config.request && { credentials: "include" }),
}).then((res) => res.json());
});
return new Environment({
store,
network,
handlerProvider: null,
});
}