Skip to content

Commit

Permalink
Merge branch 'main' of github.com:codeledge/deverything
Browse files Browse the repository at this point in the history
  • Loading branch information
ogroppo committed Sep 7, 2024
2 parents 0079cf7 + d47c276 commit ca21fbe
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 8 deletions.
6 changes: 3 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# deverything

## 1.3.1
## 1.4.0

### Patch Changes
### Minor Changes

- fix `first()` return type
- setCookie util

## 1.3.0

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "deverything",
"version": "1.3.1",
"version": "1.4.0",
"description": "Everything you need for Dev",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
Expand Down
15 changes: 15 additions & 0 deletions src/formatters/formatCookies.test.ts
Original file line number Diff line number Diff line change
@@ -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;`);
});
});
15 changes: 11 additions & 4 deletions src/formatters/formatCookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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("; ") + ";"
);
};
30 changes: 30 additions & 0 deletions src/helpers/setCookie.ts
Original file line number Diff line number Diff line change
@@ -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,
});
};

0 comments on commit ca21fbe

Please sign in to comment.