datasquirel/package-shared/utils/serialize-cookies.ts
2025-01-10 20:10:28 +01:00

50 lines
1.3 KiB
TypeScript

// @ts-check
import { CookieObject } from "../types";
/**
* # Serialize Cookies
* @description Convert cookie object to string array
*/
export default function serializeCookies({
cookies,
}: {
cookies: CookieObject[];
}): string[] {
let cookiesStringsArray: string[] = [];
for (let i = 0; i < cookies.length; i++) {
const cookieObject = cookies[i];
let cookieString = `${cookieObject.name}=${cookieObject.value}`;
if (cookieObject.maxAge) {
cookieString += `;Max-Age=${cookieObject.maxAge}`;
}
if (cookieObject.path) {
cookieString += `;Path=${cookieObject.path}`;
}
if (cookieObject.domain) {
cookieString += `;Domain=${cookieObject.domain}`;
}
if (cookieObject.secure) {
cookieString += ";Secure";
}
if (cookieObject.httpOnly) {
cookieString += ";HttpOnly";
}
if (cookieObject.sameSite) {
cookieString += `;SameSite=${cookieObject.sameSite}`;
}
if (cookieObject.expires) {
cookieString += `;expires=${cookieObject.expires}`;
}
if (cookieObject.priority) {
cookieString += `;priority=${cookieObject.priority}`;
}
cookiesStringsArray.push(cookieString);
}
return cookiesStringsArray;
}