Created
June 21, 2020 09:46
-
-
Save hyochan/9c15508cae149444f3552968e427d86b to your computer and use it in GitHub Desktop.
relay/RelayEnvironment.ts
This file contains hidden or 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
import { | |
CacheConfig, | |
Environment, | |
GraphQLResponse, | |
Network, | |
RecordSource, | |
RequestParameters, | |
Store, | |
Variables, | |
} from 'relay-runtime'; | |
import AsyncStorage from '@react-native-community/async-storage'; | |
import fetchGraphQL from './fetch'; | |
const __DEV__ = process.env.NODE_ENV === 'development'; | |
async function fetchFunction( | |
request: RequestParameters, | |
variables: Variables, | |
cacheConfig: CacheConfig, | |
): Promise<GraphQLResponse> { | |
const args = { request, variables, cacheConfig }; | |
return AsyncStorage.getItem('token').then((token) => { | |
return fetchGraphQL({ ...args, token }); | |
}); | |
} | |
export type RelayEnvironmentProps = Environment; | |
class RelayEnvironment { | |
config = { | |
network: Network.create(fetchFunction), | |
store: new Store(new RecordSource()), | |
}; | |
environment: RelayEnvironmentProps = new Environment(this.config); | |
constructor() { | |
this.resetEnvironment(); | |
} | |
getEnvironment(): RelayEnvironmentProps { | |
return this.environment; | |
} | |
resetEnvironment(): RelayEnvironmentProps { | |
if (__DEV__) console.log('relay env instance initialized'); | |
this.environment = new Environment(this.config); | |
return this.environment; | |
} | |
} | |
export default new RelayEnvironment(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment