Skip to content

Instantly share code, notes, and snippets.

@caub
Created November 23, 2017 16:12
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 caub/eb0af018e0a725733a22723ce00a63c7 to your computer and use it in GitHub Desktop.
Save caub/eb0af018e0a725733a22723ce00a63c7 to your computer and use it in GitHub Desktop.
Custom session store
const { Store } = require('express-session');
const { knex } = require('.');
class PGStore extends Store {
destroy(sid, cb) {
return knex('sessions').where('id', sid).delete().then(() => cb());
}
get(sid, cb) {
// console.log('get', sid);
return knex.raw(`SELECT user_id, perm, cookie FROM sessions LEFT JOIN users ON users.id=sessions.user_id WHERE sessions.id=? AND expire > now()`, sid)
.then(({ rows }) => cb(null, rows[0]));
}
set(sid, { user_id, cookie }, cb) {
// console.log('set', sid, user_id);
const expire = new Date(Date.now() + cookie.maxAge);
return knex.raw(`INSERT INTO sessions (id, user_id, cookie, expire) VALUES (?, ?, ?, ?)
ON CONFLICT (id)
DO UPDATE SET user_id = EXCLUDED.user_id, cookie = EXCLUDED.cookie, expire = EXCLUDED.expire`, [sid, user_id, cookie, expire])
.then(({ rows }) => cb(null, rows[0]));
}
}
module.exports = opts => new PGStore(opts);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment