Skip to content

Commit

Permalink
feat(parse): support filter option for key filtering (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
yxw007 authored May 22, 2024
1 parent cec0169 commit f7c9a14
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ export function parse(
}

const key = str.slice(index, eqIdx).trim();
if (opt?.filter && !opt?.filter(key)) {
index = endIdx + 1;
continue;
}

// only assign once
if (undefined === obj[key]) {
Expand Down
4 changes: 4 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,8 @@ export interface CookieParseOptions {
* cookie value will be returned as the cookie's value.
*/
decode?(value: string): string;
/**
* Custom function to filter parsing specific keys.
*/
filter?(key: string): boolean;
}
9 changes: 9 additions & 0 deletions test/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,14 @@ describe("cookie.parse(str, options)", () => {
}),
).toMatchObject({ foo: "bar" });
});

it("parse filter key", () => {
expect(parse("a=1;b=2", {
filter: (key) => key === "a"
})).toMatchObject({ a: "1" });

expect(parse("a=1;b=2"))
.toMatchObject({ a: "1", b: "2" });
})
});
});

0 comments on commit f7c9a14

Please sign in to comment.