Cache data
Cache data
This is for:
DeveloperIntegrations provides the ability to cache data between executions. This is presented in the form of a volatile cache, meaning you should not depend on it being available for the whole duration of your TTL.
Note
When previewing an integration, caching is limited to a single function and a single execution. To get/set a value from the cache from consecutive executions of one integration instance, you’ll need to publish your integration. |
A cache API is passed into your integration handler, which allows you to access the cache.
There are two main flows when working with the cache.
You can either use the combined get/set call by passing in a getValue
function, or you can manually get/set cache value.
Both flows are shown in the following example:
// integration.js
module.exports = async function handler ({ payload, secrets, cache }) {
// A function that calls the auth service and returns a
// promise resolving to an authenticated service token
async function authenticate () {
const { data } = await axios.post('https://my-protected-service.com/authenticate', {
headers: {
Authorization: `Bearer ${secrets.PASSWORD}`
}
})
return {
token: data.token,
ttl: data.ttl
}
}
// You can either use the combined get/set call by passing in a `getValue` function
let token1 = await cache.get('token', {
ttl: 60 * 1000,
// If there is no cached value, this function be run to retrieve the value
// It will be stored and returned
getValue: authenticate().then(data => data.token)
})
await axios.post('https://my-protected-service.com/authenticated-route', {
headers: {
Authorization: `Bearer ${token1}`
}
})
// Or you can either manually get/set cache value:
let token2 = await cache.get('token')
if (!token2) {
const { token, ttl } = await authenticate()
await cache.set('token', token, { ttl })
token2 = token
}
await axios.post('https://my-protected-service.com/authenticated-route', {
headers: {
Authorization: `Bearer ${token2}`
}
})
}
API Reference
cache.get(key: String, options: Object?) => Promise<Any>
Retrieves a cached value.
Where:
-
options.getValue: Function => Promise<Any>
if provided, and there is no cached value, will be run to retrieve a new value. The value will be set as the cached value and returned -
options.ttl: Integer
defines the TTL of theoptions.getValue
function in milliseconds. Default: 7 days
cache.set(key: String, value: Any: options: Object?) => Promise<>
Sets a value to the cache.
Where:
-
options.ttl: Integer
defines the TTL of the value being set in milliseconds. Default: 7 days
cache.del(key: String) => Promise<>
Deletes a cached value.