datasquirel/package-shared/utils/serialize-cookies.ts

50 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-12-11 03:45:29 +00:00
// @ts-check
2025-01-10 19:10:28 +00:00
import { CookieObject } from "../types";
2024-12-11 03:45:29 +00:00
/**
2025-01-10 19:10:28 +00:00
* # Serialize Cookies
* @description Convert cookie object to string array
2024-12-11 03:45:29 +00:00
*/
2025-01-10 19:10:28 +00:00
export default function serializeCookies({
cookies,
}: {
cookies: CookieObject[];
}): string[] {
let cookiesStringsArray: string[] = [];
2024-12-11 03:45:29 +00:00
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;
}