This repository has been archived by the owner on Dec 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
POST requests will set to cache, but never read from it GET requests will set to, and read from, cache. If `no-cache` is present in the `cache-control` header, a fresh/non-cached version will be retrieved, set to cache, and returned
- Loading branch information
1 parent
4bbcc73
commit d319c31
Showing
2 changed files
with
49 additions
and
5 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
const { createHash } = require('crypto'); | ||
const redis = require('./redis'); | ||
|
||
const createCacheKey = ({ url, params } = {}) => { | ||
const hash = createHash('sha256').update(JSON.stringify({ url, params })).digest('hex'); | ||
return `base_oembed:${hash}`; | ||
}; | ||
|
||
const getFor = async ({ url, params } = {}) => { | ||
const key = createCacheKey({ url, params }); | ||
const serialized = await redis.get(key); | ||
if (!serialized) return null; | ||
const cacheValue = JSON.parse(serialized); | ||
const age = Math.round((Date.now() - cacheValue.cacheTime) / 1000); | ||
return { ...cacheValue, age }; | ||
}; | ||
|
||
const setFor = async ({ url, params, data } = {}) => { | ||
const key = createCacheKey({ url, params }); | ||
const cacheValue = { data, cacheTime: Date.now() }; | ||
const ttl = 60 * 60 * 24 * 3; // cache for 72 hours | ||
await redis.set(key, JSON.stringify(cacheValue), 'EX', ttl); | ||
}; | ||
|
||
|
||
module.exports = { | ||
createCacheKey, | ||
getFor, | ||
setFor, | ||
}; |