Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(options): add allowMultiple to options #55

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
26 changes: 17 additions & 9 deletions src/cookie/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ export function parse(
throw new TypeError("argument str must be a string");
}

const obj = {};
const obj: Record<string, string> = {};
const opt = options || {};
const dec = opt.decode || decode;
const allowMultiple = opt.allowMultiple || false;

let index = 0;
while (index < str.length) {
Expand All @@ -48,16 +49,23 @@ export function parse(
continue;
}

// only assign once
if (undefined === obj[key as keyof typeof obj]) {
let val = str.slice(eqIdx + 1, endIdx).trim();
let val = str.slice(eqIdx + 1, endIdx).trim();

// quoted values
if (val.codePointAt(0) === 0x22) {
val = val.slice(1, -1);
}
// quoted values
if (val.codePointAt(0) === 0x22) {
val = val.slice(1, -1);
}

(obj as any)[key] = tryDecode(val, dec);
val = tryDecode(val, dec);

// handle multiple values for the same key
if (allowMultiple) {
pi0 marked this conversation as resolved.
Show resolved Hide resolved
obj[key] =
obj[key] === undefined || obj[key] === "" ? val : `${obj[key]},${val}`;
} else {
if (obj[key] === undefined) {
obj[key] = val;
}
}

index = endIdx + 1;
Expand Down
4 changes: 4 additions & 0 deletions src/cookie/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,8 @@ export interface CookieParseOptions {
* Custom function to filter parsing specific keys.
*/
filter?(key: string): boolean;
/**
* Flag to allow to return multiple values when cookie is duplicated.
*/
allowMultiple?: boolean;
}
21 changes: 21 additions & 0 deletions test/cookie-parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,27 @@ describe("cookie.parse(str)", () => {
bar: "bar",
});
});

it("should return duplicated cookies values if `allowMultiple` is set", () => {
expect(
parse("foo=%1;bar=bar;foo=boo", { allowMultiple: true }),
).toMatchObject({
foo: "%1,boo",
bar: "bar",
});
expect(
parse("foo=false;bar=bar;foo=true", { allowMultiple: true }),
).toMatchObject({
foo: "false,true",
bar: "bar",
});
expect(
parse("foo=;bar=bar;foo=boo", { allowMultiple: true }),
).toMatchObject({
foo: "boo",
bar: "bar",
});
});
});

describe("cookie.parse(str, options)", () => {
Expand Down