From 878f8c058bfd233e1b4f20b34bc0c8ca21ecffca Mon Sep 17 00:00:00 2001 From: Anton Sabotovich Date: Wed, 25 Sep 2024 20:00:06 +0300 Subject: [PATCH] feat: support cookies utils --- src/utils/cookies.ts | 25 +++++++++++++++++++++++++ src/utils/index.ts | 1 + 2 files changed, 26 insertions(+) create mode 100644 src/utils/cookies.ts diff --git a/src/utils/cookies.ts b/src/utils/cookies.ts new file mode 100644 index 00000000..06e70621 --- /dev/null +++ b/src/utils/cookies.ts @@ -0,0 +1,25 @@ +type CookiesOptions = Record; + +export const setCookie = (name: string, value: string | number | boolean, defaults: CookiesOptions = {}) => { + const options: CookiesOptions = { + path: '/', + ...defaults, + }; + + document.cookie = Object.keys(options).reduce((cookie, optionKey) => { + const optionValue = options[optionKey]; + const cookieWithOption = `${cookie}; ${optionKey}`; + + if (optionValue !== true) { + return `${cookieWithOption}=${optionValue}`; + } + + return cookieWithOption; + }, `${encodeURIComponent(name)}=${encodeURIComponent(value)}`); +}; + +export const deleteCookie = (name: string) => { + setCookie(name, '', { + 'max-age': -999, + }); +}; diff --git a/src/utils/index.ts b/src/utils/index.ts index 1257c7de..3455eb32 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -6,3 +6,4 @@ export * from './translit'; export * from './upload'; export * from './worker'; export * from './date'; +export * from './cookies';