Skip to content

Instantly share code, notes, and snippets.

@maraisr
Last active July 1, 2020 13:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save maraisr/32a7b0c1a464d52741729ced141065a9 to your computer and use it in GitHub Desktop.
Save maraisr/32a7b0c1a464d52741729ced141065a9 to your computer and use it in GitHub Desktop.
import {
Environment,
FetchFunction,
Network,
RecordSource,
RequestParameters,
Store,
Variables,
} from 'relay-runtime';
import fetch from 'isomorphic-unfetch';
import { RecordMap } from 'relay-runtime/lib/store/RelayStoreTypes';
const fetchQuery: FetchFunction = async (
params: RequestParameters,
variables: Variables,
) => {
const response: Response = await fetch(`http://my-api.com/graph/graphql`, {
method: 'POST',
cache: 'no-cache',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: params.text,
variables,
doc_id: params.id,
}),
});
const data = await response.json();
const hasError = Array.isArray(data?.errors);
if (hasError) {
throw new GraphError(data.errors);
}
return data;
};
const network = Network.create(fetchQuery);
const createEnvironment = (records: RecordMap = {}): Environment => {
const source = new RecordSource(records);
const store = new Store(source);
return new Environment({
configName: 'standard',
network,
store,
});
};
let memoEnv: Environment = null;
export const getRelayEnvironment = (records: RecordMap = {}) => {
if (!process.browser) return createEnvironment(records);
if (memoEnv === null) {
memoEnv = createEnvironment(records);
}
return memoEnv;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment