Created
June 20, 2019 09:49
-
-
Save Developerayo/bec654e28bc9477a51267fd77682bfd0 to your computer and use it in GitHub Desktop.
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
import {InMemoryCache} from 'apollo-cache-inmemory'; | |
import {ApolloLink} from 'apollo-client-preset'; | |
import {ApolloClient} from 'apollo-client'; | |
import {withClientState} from 'apollo-link-state'; | |
import gql from 'graphql-tag'; | |
import {graphql} from 'react-apollo'; | |
import compose from 'recompose/compose'; | |
/* | |
Defaults | |
*/ | |
const DataDefaults = { | |
currentDatas: [], | |
}; | |
/* | |
GraphQL | |
*/ | |
const DataQuery = gql` | |
query GetData { | |
currentDatas @client | |
} | |
`; | |
const clearDataQuery = gql` | |
mutation clearData { | |
clearData @client | |
} | |
`; | |
const addDataQuery = gql` | |
mutation addData($item: String) { | |
addData(item: $item) @client | |
} | |
`; | |
/* | |
Cache Mutations | |
*/ | |
const addData = (_obj, {item}, {cache}) => { | |
const query = DataQuery; | |
// Read the Data's from the cache | |
const {currentDatas} = cache.readQuery({query}); | |
// Add the item to the current Datas | |
const updatedDatas = currentDatas.concat(item); | |
// Update the cached Datas | |
cache.writeQuery({query, data: {currentDatas: updatedDatas}}); | |
return null; | |
}; | |
const clearData = (_obj, _args, {cache}) => { | |
cache.writeQuery({query: DataQuery, data: DataDefaults}); | |
return null; | |
}; | |
/* | |
Store | |
*/ | |
// Set up Cache | |
const cache = new InMemoryCache(); | |
// Set up Local State | |
const stateLink = withClientState({ | |
cache, | |
defaults: DataDefaults, | |
resolvers: { | |
Mutation: { | |
addData, | |
clearData, | |
}, | |
}, | |
}); | |
// Initialize the Apollo Client | |
const Client = new ApolloClient({ | |
link: ApolloLink.from([ | |
stateLink, | |
]), | |
cache: cache, | |
}); | |
/* | |
Helpers | |
*/ | |
const DataQueryHandler = { | |
props: ({ownProps, data: {currentDatas = []}}) => ({ | |
...ownProps, | |
currentDatas, | |
}), | |
}; | |
const withData = compose( | |
graphql(DataQuery, DataQueryHandler), | |
graphql(addDataQuery, {name: 'addDataMutation'}), | |
graphql(clearDataQuery, {name: 'clearDataMutation'}), | |
); | |
export { | |
Client, | |
withData | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment