Last active
March 21, 2019 00:28
-
-
Save riccoski/224bfaa911fb8854bb19e0a609748e34 to your computer and use it in GitHub Desktop.
A way to add TTL to Apollo Client query
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 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 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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