UNPKG

hono-sess

Version:

A Simple Session Middleware for Hono

61 lines (60 loc) 1.56 kB
"use strict"; import { Cookie } from "./cookie.js"; export class Session { #req; #_id; cookie; get id() { return this.#_id; } constructor(req, data) { this.#req = req; this.#_id = req.sessionID; if (req.session?.cookie) { this.cookie = new Cookie(req.session.cookie); } else { this.cookie = new Cookie(); } if (typeof data === "object" && data !== null) { for (const prop in data) { if (!(prop in this)) { this[prop] = data[prop]; } } } } touch() { return this.resetMaxAge(); } resetMaxAge() { this.cookie.maxAge = this.cookie.originalMaxAge ?? undefined; return this; } save(fn) { this.#req.sessionStore.set(this.id, this, fn || (() => { })); return this; } reload(fn) { const req = this.#req; const store = this.#req.sessionStore; store.get(this.id, (err, sess) => { if (err) return fn(err); if (!sess) return fn(new Error("failed to load session")); store.createSession(req, sess); fn(); }); return this; } destroy(fn) { delete this.#req.session; this.#req.sessionStore.destroy(this.id, fn || (() => { })); return this; } regenerate(fn) { this.#req.sessionStore.regenerate(this.#req, fn); return this; } }