Skip to content

Instantly share code, notes, and snippets.

@riccoski
Last active March 21, 2019 00:28
Show Gist options
  • Save riccoski/224bfaa911fb8854bb19e0a609748e34 to your computer and use it in GitHub Desktop.
Save riccoski/224bfaa911fb8854bb19e0a609748e34 to your computer and use it in GitHub Desktop.
A way to add TTL to Apollo Client query
import client from './client'
import gql from 'graphql-tag';
const queryPlus = async (props) => {
const { cacheId: id, ttl = 900000, ...queryProps } = props
if (!id)
throw new Error('cacheId is required')
const fragment = gql`
fragment cacheRef on CacheRef {
id
timestamp
ttl
}
`
try {
const cacheRef = function() {
const _item = client.readFragment({
id,
fragment
});
const hasExpired = function() {
const now = new Date()
if (_item) {
return ((now - new Date(_item.timestamp)) >= (ttl || _item.ttl))
}
return true
}()
return {
hasExpired: hasExpired
}
}()
const res = await client.query({
...queryProps,
fetchPolicy: cacheRef.hasExpired ? 'network-only' : 'cache-first'
})
// Set the cache item
if (cacheRef.hasExpired) {
const timestamp = new Date().toString()
client.writeFragment({
id,
fragment,
data: {
id,
timestamp,
ttl,
__typename: 'CacheRef'
},
});
}
return Promise.resolve(res)
} catch (e) {
return Promise.reject(e)
}
}
export { client, queryPlus };
// Usage
const res = await queryPlus({
query,
variables,
cacheId: `User:${id}`,
ttl: 450000
})
@riccoski
Copy link
Author

riccoski commented Jun 7, 2018

@mshwery
Copy link

mshwery commented Jun 30, 2018

Wouldn't you want the cache id to be generated in a similar way to apollo-client, e.g. serialize the query + variables?

@riccoski
Copy link
Author

@mshwery you're right (though it would make for a long id) but it could be good for a default ID with the option to override it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment