Skip to content

Commit

Permalink
add support for easy JSON stringifying jar
Browse files Browse the repository at this point in the history
  • Loading branch information
jd1378 committed Jan 31, 2021
1 parent 8899d0d commit 015b073
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
14 changes: 12 additions & 2 deletions CookieJar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,15 @@ export class CookieJar {
/**
* @param cookies - the cookies array to initialize with
*/
constructor(cookies?: Array<Cookie>) {
constructor(cookies?: Array<Cookie> | Array<CookieOptions>) {
if (cookies?.length) {
this.cookies = cookies;
if (typeof (cookies[0] as Cookie).isValid === "function") {
this.cookies = cookies as Array<Cookie>;
} else {
for (const cookie of cookies) {
this.cookies.push(new Cookie(cookie));
}
}
}
}

Expand Down Expand Up @@ -179,4 +185,8 @@ export class CookieJar {
.join("; ");
return cookiesToSend;
}

toJSON() {
return this.cookies;
}
}
33 changes: 33 additions & 0 deletions cookie_jar_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,36 @@ Deno.test("CookieJar.getCookieString()", () => {
"",
);
});

Deno.test("CookieJar json serialization", () => {
const cookieStr1 = "test=nop; path=/sth; domain=.example.com";
const cookieStr2 = "foo=bar; path=/sth; domain=.example.com";
const cookie1 = Cookie.from(cookieStr1);
const cookie2 = Cookie.from(cookieStr2);

const cookieJar = new CookieJar([
cookie1,
cookie2,
]);

const newCookieJar = new CookieJar(JSON.parse(JSON.stringify(cookieJar)));

// our before-serialized jar
assertStrictEquals(
cookieJar.getCookieString("example.com"),
"test=nop; foo=bar",
);
assertStrictEquals(
cookieJar.getCookieString("notexample.com"),
"",
);
// our new parsed cookie jar
assertStrictEquals(
newCookieJar.getCookieString("example.com"),
"test=nop; foo=bar",
);
assertStrictEquals(
newCookieJar.getCookieString("notexample.com"),
"",
);
});

0 comments on commit 015b073

Please sign in to comment.