Skip to content

Instantly share code, notes, and snippets.

@bchiang7
Created November 8, 2019 03:29
Show Gist options
  • Save bchiang7/b5f8ce1f28e82a7d6f7079beb00cca35 to your computer and use it in GitHub Desktop.
Save bchiang7/b5f8ce1f28e82a7d6f7079beb00cca35 to your computer and use it in GitHub Desktop.
/**
* Fetches the session user from cache if it exists, or sets it if it does not
*/
const getOrSetUserFromCache = async headers => {
const User = require('../models/User');
const userUid = headers['x-userid'];
try {
const firebaseUserUid = await User.getUserIdFromToken(headers.authorization);
if (!userUid || firebaseUserUid !== userUid) {
userCache.del(`firebase-${userUid}`);
return User.getCurrentUserByToken(headers.authorization);
}
const userFromCache = userCache.get(`firebase-${userUid}`);
if (userFromCache) {
return userFromCache;
}
const user = await User.getCurrentUserByToken(headers.authorization);
userCache.set(`firebase-${userUid}`, user, FIVE_MINUTES); // Set TTL
return user;
} catch (e) {
throw new Error('Invalid user token');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment