|
1 | 1 | // Copyright The OpenTelemetry Authors |
2 | 2 | // SPDX-License-Identifier: Apache-2.0 |
3 | 3 |
|
| 4 | +import { getCookie, setCookie } from 'cookies-next'; |
4 | 5 | import { v4 } from 'uuid'; |
5 | | -import { getCookie } from "cookies-next"; |
6 | 6 |
|
7 | 7 | interface ISession { |
8 | 8 | userId: string; |
9 | 9 | currencyCode: string; |
10 | 10 | } |
11 | 11 |
|
12 | | -const sessionKey = 'session'; |
13 | | -const defaultSession: ISession = { |
14 | | - userId: getCookie('USERID') as string || v4(), |
15 | | - currencyCode: 'USD', |
16 | | -}; |
| 12 | +const defaultUUID = v4(); |
| 13 | +const defaultCurrencyCode = 'USD'; |
17 | 14 |
|
18 | | -const SessionGateway = () => ({ |
19 | | - getSession(): ISession { |
20 | | - if (typeof window === 'undefined') return defaultSession; |
21 | | - const sessionString = localStorage.getItem(sessionKey); |
22 | | - |
23 | | - if (!sessionString) localStorage.setItem(sessionKey, JSON.stringify(defaultSession)); |
| 15 | +function getDefaultSession(userId?: string): ISession { |
| 16 | + return { |
| 17 | + userId: userId ?? defaultUUID, |
| 18 | + currencyCode: defaultCurrencyCode, |
| 19 | + }; |
| 20 | +} |
24 | 21 |
|
25 | | - return JSON.parse(sessionString || JSON.stringify(defaultSession)) as ISession; |
| 22 | +const SessionGateway = () => ({ |
| 23 | + getSession(userId?: string): ISession { |
| 24 | + if (typeof window === 'undefined') { |
| 25 | + return getDefaultSession(userId); |
| 26 | + } |
| 27 | + |
| 28 | + const cookieUserId = getCookie('USERID') as string; |
| 29 | + const currencyCode = getCookie('currencyCode') as string; |
| 30 | + |
| 31 | + return { |
| 32 | + userId: cookieUserId || userId || defaultUUID, |
| 33 | + currencyCode: currencyCode || defaultCurrencyCode, |
| 34 | + }; |
26 | 35 | }, |
27 | 36 | setSessionValue<K extends keyof ISession>(key: K, value: ISession[K]) { |
28 | | - const session = this.getSession(); |
29 | | - |
30 | | - localStorage.setItem(sessionKey, JSON.stringify({ ...session, [key]: value })); |
| 37 | + setCookie(key, value); |
31 | 38 | }, |
32 | 39 | }); |
33 | 40 |
|
|
0 commit comments