Created
November 8, 2019 03:29
-
-
Save bchiang7/b5f8ce1f28e82a7d6f7079beb00cca35 to your computer and use it in GitHub Desktop.
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
/** | |
* 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