@otterhttp/session
Version:
Simple promise-based session utility for otterhttp
72 lines (67 loc) • 2.53 kB
TypeScript
import { Request, Response } from '@otterhttp/app';
import { SerializeOptions } from '@otterhttp/cookie';
declare const isTouched: unique symbol;
declare const isDestroyed: unique symbol;
declare const isNew: unique symbol;
type SessionRecord = Record<string, unknown>;
type SessionData<T = SessionRecord> = {
cookie: Cookie;
} & T;
type Session<T extends SessionRecord = SessionRecord> = {
id: string;
touch(): Promise<void>;
commit(): Promise<void>;
destroy(): Promise<void>;
[isNew]?: boolean;
[isTouched]?: boolean;
[isDestroyed]?: boolean;
} & SessionData<T>;
type Cookie = {
httpOnly: boolean;
path: string;
domain?: string | undefined | null;
secure: boolean;
sameSite?: boolean | "lax" | "strict" | "none" | undefined | null;
} & ({
maxAge?: undefined | null;
expires?: undefined | null;
} | {
maxAge: number;
expires: Date;
});
type SetCookieOptions = SerializeOptions & {
/**
* `otterhttp` cookie `sign` function, will be passed to `res.cookie`.
* @default undefined
*/
sign?: ((value: string) => string) | null | undefined;
};
interface SessionStore {
get(sid: string): Promise<SessionData | null | undefined>;
set(sid: string, sess: SessionData): Promise<void>;
destroy(sid: string): Promise<void>;
touch?(sid: string, sess: SessionData): Promise<void>;
}
interface Options {
store?: SessionStore | undefined;
genid?: (() => string) | undefined;
touchAfter?: number | undefined;
cookie?: (SetCookieOptions & {
name?: string | null | undefined;
/**
* `otterhttp` cookie 'unsign' function, will be used to unsign session cookies.
*
* You must ensure that signed session cookies are not matched by your `otterhttp` `App`'s configured
* `signedCookieMatcher`. Otherwise, `otterhttp` will attempt to unsign session cookies using the `App`'s configured
* `cookieUnsigner` instead, and unsigning with this function will not be attempted.
* @default undefined
*/
unsign?: ((signedValue: string) => string) | null | undefined;
}) | undefined;
}
declare function session<T extends SessionRecord = SessionRecord, Req extends Request & {
session?: Session<T>;
} = Request & {
session?: Session<T>;
}, Res extends Response<Req> = Response<Req>>(options?: Options): (req: Req, res: Res) => Promise<Session<T>>;
export { type Options, type Session, type SessionData, type SessionStore, session as default };