Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 51 additions & 10 deletions src/Utilities/Utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,56 @@ type Cookie = {
secure?: boolean;
};

export const setCookie = (
headers: Headers,
cookie: Cookie
): Headers => {
throw new Error('unimplemented');

export const setCookie = (headers: Headers) => (cookie: Cookie): Headers => {
const {
name,
value,
domain,
path = '/',
expires,
httpOnly,
maxAge,
sameSite,
secure,
} = cookie;

let cookieString = `${name}=${value}; Path=${path}`;
if (domain) cookieString += `; Domain=${domain}`;
if (maxAge) cookieString += `; Max-Age=${maxAge}`;
if (expires !== undefined) {
cookieString += `; Expires=${expires === 0 ? 'Thu, 01 Jan 1970 00:00:00 GMT' : (expires as Date).toUTCString()}`;
}
if (secure) cookieString += `; Secure`;
if (httpOnly) cookieString += `; HttpOnly`;
if (sameSite) cookieString += `; SameSite=${sameSite}`;

const key = Object.keys(headers).find(k => k.toLowerCase() === 'set-cookie') || 'set-cookie';
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it necessary to to iterate all the headers every time? Why not do

const existing = headers['Set-Cookie'] ?? headers['set-cookie'];

const existing = headers[key] || [];

return {
...headers,
[key]: [...existing, cookieString],
};
};

export const getCookie = (
headers: Headers
) => (name: string): string => {
throw new Error('unimplemented');
}

export const getCookie = (headers: Headers) => (name: string): Cookie | undefined => {
const cookieKey = Object.keys(headers).find(k => k.toLowerCase() === 'cookie');
Copy link
Collaborator

@sharmrj sharmrj Jun 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, instead of iterating through the headers, couldn't we do const cookies = headers['Cookie'] ?? headers ['cookie'];

if (!cookieKey) return undefined;

const cookieString = headers[cookieKey].join('; ');
const cookieParts = cookieString.split(';').map(c => c.trim());

Comment on lines +73 to +75
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why join only to immediately split again?

for (const part of cookieParts) {
const [k, ...rest] = part.split('=');
if (k === name) {
return {
name: k,
value: rest.join('=')
};
}
}

return undefined;
};