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(parse): support filter option for key filtering #35

Merged
merged 2 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
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
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" });
})
});
});
Loading