diff --git a/src/formatters/formatCookies.test.ts b/src/formatters/formatCookies.test.ts new file mode 100644 index 0000000..8d9e993 --- /dev/null +++ b/src/formatters/formatCookies.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, test } from "@jest/globals"; +import { formatCookies } from "./formatCookies"; + +describe("formatCookies", () => { + test("should return the same number if test is under a thousand", () => { + expect( + formatCookies({ + num: 123, + bool: true, + string: "string", + undef: undefined, + }) + ).toBe(`num=123; bool=true; string=string;`); + }); +}); diff --git a/src/formatters/formatCookies.ts b/src/formatters/formatCookies.ts index 30f065b..76ad810 100644 --- a/src/formatters/formatCookies.ts +++ b/src/formatters/formatCookies.ts @@ -3,10 +3,17 @@ import { PlainObject } from "../types/Object"; /** * * @example formatCookies({}) => "" - * @example formatCookies({ session: "123", _ga: 123 }) => "session=123; _ga=123" + * @example formatCookies({ session: "123", _ga: 123 }) => "session=123; _ga=123;" */ export const formatCookies = (object: PlainObject): string => { - return Object.entries(object) - .map(([key, value]) => `${key}=${value}`) - .join("; "); + return ( + Object.entries(object) + .reduce((acc: string[], [key, value]) => { + // allow nulls to be set? + if (value !== undefined) acc.push(`${key}=${value}`); + + return acc; + }, []) + .join("; ") + ";" + ); }; diff --git a/src/helpers/setCookie.ts b/src/helpers/setCookie.ts new file mode 100644 index 0000000..41eb3cc --- /dev/null +++ b/src/helpers/setCookie.ts @@ -0,0 +1,30 @@ +import { formatCookies } from "../formatters"; + +/** + * Set a client cookie by name, works only in the browser + * @param name - required + * @param value - required, any value tha can be serialized + * @param domain - optional, defailts to current domain + * @param maxAgeSeconds - optional, defaults to "Session" + */ +export const setCookie = ({ + domain, + maxAgeSeconds, + name, + value, +}: { + domain?: string; + maxAgeSeconds?: number; + name: string; + value: any; +}): void => { + if (typeof document === "undefined") { + return; + } + + document.cookie = formatCookies({ + [name]: value, + domain, + "max-age": maxAgeSeconds, + }); +};