Created
March 21, 2021 18:48
-
-
Save jean-leonco/bde39718a7697a81188c08ca2257b0a5 to your computer and use it in GitHub Desktop.
Simple Relay environment with auth header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reference: https://relay.dev/docs/guides/network-layer | |
import { Environment, Network, RecordSource, Store } from 'relay-runtime'; | |
// Function to get the authentication token | |
export const getToken = () => { | |
return localStorage.getItem('authentication_token'); | |
}; | |
// Define a function that fetches the results of an operation (query/mutation/etc) | |
// and returns its results as a Promise: | |
function fetchQuery(operation, variables, cacheConfig, uploadables) { | |
const token = getToken(); | |
return fetch('/graphql', { | |
method: 'POST', | |
headers: { | |
// Add authentication and other headers here | |
authorization: token ? `Bearer ${token}` : null, | |
'content-type': 'application/json', | |
}, | |
body: JSON.stringify({ | |
query: operation.text, // GraphQL text from input | |
variables, | |
}), | |
}).then((response) => { | |
return response.json(); | |
}); | |
} | |
// Create a network layer from the fetch function | |
const network = Network.create(fetchQuery); | |
const store = new Store(new RecordSource()); | |
const environment = new Environment({ | |
network, | |
store, | |
// ... other options | |
}); | |
export default environment; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment