Last active
November 1, 2023 23:46
-
-
Save the-vampiire/a564af41ed0ce8eb7c30dbe6c0f627d8 to your computer and use it in GitHub Desktop.
express supertest / superagent utility for accessing response cookies as objects
wrote this because parsing the res.headers[set-cookie]
is a pain in the ass when needing to verify that cookies were set properly. extracts the set-cookie
header from an express
response using supertest
and provides an object of the following shape:
const cookies = {
cookieName: {
value: 'cookie value',
flags: {
flagName: 'flag value',
booleanFlag: true, // boolean flags (no value) are given true as their value
},
},
};
In case anyone is looking for a Typescript version of this
/**
* Format the cookie flags
*
* @example
* ```
* { Path: '/', Secure: true, SameSite: 'Lax' }
* ```
*/
const shapeFlags = (flags: Array<string>) =>
flags.reduce((shapedFlags, flag) => {
const [flagName, rawValue] = flag.split('=');
// edge case where a cookie has a single flag and "; " split results in trailing ";"
const value = rawValue ? rawValue.replace(';', '') : true;
return { ...shapedFlags, [flagName]: value };
}, {});
/**
* The interface for structure in which a cookie is
* returned by `extractCookies`
*/
interface ExtractedCookie {
value: string;
flags: Record<string, string | boolean | number>;
}
/**
* Extract cookies from headers
*
* @param headers The headers of the response
*
* @reference https://gist.github.com/the-vampiire/a564af41ed0ce8eb7c30dbe6c0f627d8
*/
export const extractCookies = (
headers: Record<string, string | Array<string | number>>
): Record<string, ExtractedCookie> => {
const cookies = headers['set-cookie'] as Array<string>;
return cookies.reduce((shapedCookies, cookieString) => {
const [rawCookie, ...flags] = cookieString.split('; ');
const [cookieName, value] = rawCookie.split('=');
return { ...shapedCookies, [cookieName]: { value, flags: shapeFlags(flags) } };
}, {});
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage