Skip to content

Commit

Permalink
fix(parse): allowMultiple option returns all results within the same …
Browse files Browse the repository at this point in the history
…string
  • Loading branch information
jpsc committed Oct 4, 2024
1 parent 1d08e23 commit 7c772ec
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 12 deletions.
13 changes: 4 additions & 9 deletions src/cookie/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ import type { CookieParseOptions } from "./types";
export function parse(
str: string,
options?: CookieParseOptions,
): Record<string, string | string[]> {
): Record<string, string> {
if (typeof str !== "string") {
throw new TypeError("argument str must be a string");
}

const obj: Record<string, string | string[]> = {};
const obj: Record<string, string> = {};
const opt = options || {};
const dec = opt.decode || decode;
const allowMultiple = opt.allowMultiple || false;
Expand Down Expand Up @@ -60,13 +60,8 @@ export function parse(

// handle multiple values for the same key
if (allowMultiple) {
if (obj[key] === undefined) {
obj[key] = val; // first occurrence, assign as string
} else if (typeof obj[key] === "string") {
obj[key] = [obj[key], val]; // convert string to array
} else {
(obj[key] as string[]).push(val); // append to array
}
obj[key] =
obj[key] === undefined || obj[key] === "" ? val : `${obj[key]},${val}`;
} else {
if (obj[key] === undefined) {
obj[key] = val;
Expand Down
6 changes: 3 additions & 3 deletions test/cookie-parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,19 +66,19 @@ describe("cookie.parse(str)", () => {
expect(
parse("foo=%1;bar=bar;foo=boo", { allowMultiple: true }),
).toMatchObject({
foo: ["%1", "boo"],
foo: "%1,boo",
bar: "bar",
});
expect(
parse("foo=false;bar=bar;foo=true", { allowMultiple: true }),
).toMatchObject({
foo: ["false", "true"],
foo: "false,true",
bar: "bar",
});
expect(
parse("foo=;bar=bar;foo=boo", { allowMultiple: true }),
).toMatchObject({
foo: ["", "boo"],
foo: "boo",
bar: "bar",
});
});
Expand Down

0 comments on commit 7c772ec

Please sign in to comment.