Created
November 23, 2017 16:12
-
-
Save caub/eb0af018e0a725733a22723ce00a63c7 to your computer and use it in GitHub Desktop.
Custom session store
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
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