Skip to content

Instantly share code, notes, and snippets.

@astrotars
Last active July 17, 2018 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astrotars/0b58efae91b8679440c90fd16db0ef6d to your computer and use it in GitHub Desktop.
Save astrotars/0b58efae91b8679440c90fd16db0ef6d to your computer and use it in GitHub Desktop.
async function getInterestMap() {
// the cache key is interests concatenated with a v and the latest application version number
const cacheKey = `interests:v${packageInfo.version.replace(/\./g, ':')}`;
// this portion of the code get the cached data using the cache key
let str = await cache.get(cacheKey);
// and this parses the JSON string into an object
let interestMap = JSON.parse(str);
// in the event that our cache has expired or is new, we add it back to Redis or refresh the cache
if (!interestMap) {
// we'll populate this in a bit
interestMap = {};
// select featured rss and podcasts synchronously
const rss = await RSS.findFeatured();
const podcast = await Podcast.findFeatured();
// loop over the concatenated array
for (let p of [...rss, ...podcast]) {
let k = p.interest || 'featured'; // if it doesn't have an iterest, make it featured
let d = p.toObject(); // convert the mongoose object to a plain javascript object
d.type = p.constructor.modelName == 'RSS' ? 'rss' : 'podcast'; // some mongoose required magic
if (!(k in interestMap)) {
interestMap[k] = [];
}
// push the key and value into the interestMap array
interestMap[k].push(d);
}
// set the cache
let cached = await cache.set(
cacheKey, // generated cache key for uniqeness
JSON.stringify(interestMap), // interest object as JSON
'EX', // expiration command
60 * 30, // expiration
);
}
return interestMap;
}
// called in the user signup method (not shown)
const interests = await interestMap();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment