Skip to content

Instantly share code, notes, and snippets.

@alex-hladun
Last active November 1, 2021 23:27
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 alex-hladun/a01d3281f08e1a0df9e3e7677f1c1279 to your computer and use it in GitHub Desktop.
Save alex-hladun/a01d3281f08e1a0df9e3e7677f1c1279 to your computer and use it in GitHub Desktop.
Saving & retrieving sessions in Redis
// Save a session for a user and their online status
saveSession(id: string, { username, connected }: { [key: string]: string }) {
this.redisClient
.multi()
.hmset(`session:${id}`, "username", username, "connected", connected)
.expire(`session:${id}`, SESSION_TTL)
.exec();
}
// Retrieve a user's session
findSession(id: String): Promise<{username: string, online: boolean}[]> {
return new Promise((resolve, reject) =>
this.redisClient.hmget(
`session:${id}`,
"username",
"connected",
(err: Error | null, valueArray: string[] | null) => {
if (valueArray) {
return resolve(mapSession(valueArray));
}
if (err) {
reject(err);
}
reject();
}
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment