datasquirel/package-shared/utils/cookies-actions.ts
Benjamin Toby 7e8bb37c09 Updates
2025-07-05 14:59:30 +01:00

75 lines
2.0 KiB
TypeScript

import * as http from "http";
import { CookieOptions } from "../types";
import { CookieNames } from "../dict/cookie-names";
export function setCookie(
res: http.ServerResponse,
name: (typeof CookieNames)[keyof typeof CookieNames],
value: string,
options: CookieOptions = {}
): void {
const cookieParts: string[] = [
`${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
];
if (options.expires) {
cookieParts.push(`Expires=${options.expires.toUTCString()}`);
}
if (options.maxAge !== undefined) {
cookieParts.push(`Max-Age=${options.maxAge}`);
}
if (options.path) {
cookieParts.push(`Path=${options.path}`);
}
if (options.domain) {
cookieParts.push(`Domain=${options.domain}`);
}
if (options.secure) {
cookieParts.push("Secure");
}
if (options.httpOnly) {
cookieParts.push("HttpOnly");
}
res.setHeader("Set-Cookie", cookieParts.join("; "));
}
export function getCookie(
req: http.IncomingMessage,
name: (typeof CookieNames)[keyof typeof CookieNames]
): string | null {
const cookieHeader = req.headers.cookie;
if (!cookieHeader) return null;
const cookies = cookieHeader
.split(";")
.reduce((acc: { [key: string]: string }, cookie: string) => {
const [key, val] = cookie.trim().split("=").map(decodeURIComponent);
acc[key] = val;
return acc;
}, {});
return cookies[name] || null;
}
export function updateCookie(
res: http.ServerResponse,
name: (typeof CookieNames)[keyof typeof CookieNames],
value: string,
options: CookieOptions = {}
): void {
setCookie(res, name, value, options);
}
export function deleteCookie(
res: http.ServerResponse,
name: (typeof CookieNames)[keyof typeof CookieNames],
options: CookieOptions = {}
): void {
setCookie(res, name, "", {
...options,
expires: new Date(0),
maxAge: 0,
});
}