-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathserverCookie.ts
More file actions
69 lines (62 loc) · 1.91 KB
/
serverCookie.ts
File metadata and controls
69 lines (62 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { createSignal, createEffect, Signal } from "solid-js";
import { isServer } from "solid-js/web";
import { parseCookie } from "solid-start";
import { useRequest } from "solid-start/server";
export type MaxAgeOptions = {
/**
* The maximum age of the cookie in seconds. Defaults to 1 year.
*/
cookieMaxAge?: number;
};
export type ServerCookieOptions<T = string> = MaxAgeOptions & {
/**
* A function to deserialize the cookie value to be used as signal value
*/
deserialize?: (str: string | undefined) => T;
/**
* A function to serialize the signal value to be used as cookie value
*/
serialize?: (value: T) => string;
};
const YEAR = 365 * 24 * 60 * 60;
/**
* A primitive for creating a cookie that can be accessed isomorphically on the client, or the server
*
* @param name The name of the cookie to be set
* @param options Options for the cookie {@see ServerCookieOptions}
* @return Returns an accessor and setter to manage the user's current theme
*/
export function createServerCookie<T>(
name: string,
options: ServerCookieOptions<T> & {
deserialize: (str: string | undefined) => T;
serialize: (value: T) => string;
},
): Signal<T>;
export function createServerCookie(
name: string,
options?: ServerCookieOptions,
): Signal<string | undefined>;
export function createServerCookie<T>(
name: string,
options?: ServerCookieOptions<T | undefined>,
): Signal<T | undefined> {
const {
deserialize = (v: any) => v as T,
serialize = String,
cookieMaxAge = YEAR,
} = options ?? {};
const [cookie, setCookie] = createSignal(
deserialize(
parseCookie(isServer ? useRequest().request.headers.get("cookie") ?? "" : document.cookie)[
name
],
),
);
createEffect(p => {
const string = serialize(cookie());
if (p !== string) document.cookie = `${name}=${string};max-age=${cookieMaxAge}`;
return string;
});
return [cookie, setCookie];
}