|
- import { IncomingMessage, ServerResponse } from 'http';
- import * as nookies from 'nookies';
-
- const COMMON_COOKIE_CONFIG = {
- path: '/',
- httpOnly: true,
- };
-
- const COMMON_SET_COOKIE_CONFIG = {
- ...COMMON_COOKIE_CONFIG,
- maxAge: 30 * 24 * 60 * 60,
- };
-
- const cookieKeys: Record<string, string> = {};
-
- export const BODY_COOKIE_KEY = 'b' as const;
- export const STATUS_CODE_COOKIE_KEY = 'sc' as const;
- export const STATUS_MESSAGE_COOKIE_KEY = 'sm' as const;
- export const CONTENT_TYPE_COOKIE_KEY = 'ct' as const;
-
- export class CookieManager {
- private readonly ctx: { req: IncomingMessage, res: ServerResponse<IncomingMessage> };
-
- constructor(ctx: { req: IncomingMessage, res: ServerResponse<IncomingMessage> }) {
- // noop
- this.ctx = ctx;
- }
-
- private static generateCookieKey(key: string) {
- return `if${key}${Date.now()}`;
- }
-
- setCookie(key: string, value: string) {
- nookies.setCookie(
- this.ctx,
- cookieKeys[key] = CookieManager.generateCookieKey(key),
- value,
- COMMON_SET_COOKIE_CONFIG,
- );
- }
-
- unsetCookie(key: string) {
- nookies.destroyCookie(this.ctx, cookieKeys[key], COMMON_COOKIE_CONFIG);
- }
-
- hasCookie(key: string) {
- const cookies = nookies.parseCookies(this.ctx);
- return cookieKeys[key] in cookies;
- }
-
- getCookie(key: string) {
- const cookies = nookies.parseCookies(this.ctx);
- return cookies[cookieKeys[key]];
- }
- }
|