|
| 1 | +import Cookies from 'js-cookie' |
| 2 | +import { ref, Ref } from '@vue/composition-api' |
| 3 | + |
| 4 | +type CookieValueType = string | JSON |
| 5 | + |
| 6 | +const tryParse = (val: string, enableParsing: boolean) => { |
| 7 | + if (!enableParsing) return val |
| 8 | + try { |
| 9 | + return JSON.parse(val) |
| 10 | + } catch (err) { |
| 11 | + return val |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +const tryStringify = (val: CookieValueType, enableParsing: boolean) => { |
| 16 | + if (!enableParsing) return val |
| 17 | + try { |
| 18 | + return JSON.stringify(val) |
| 19 | + } catch (err) { |
| 20 | + return val |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +export function useCookie(cookieName: string, enableParseJSON = false) { |
| 25 | + const getCookie = () => { |
| 26 | + const cookieVal = Cookies.get(cookieName) |
| 27 | + if (typeof cookieVal === 'undefined') return null |
| 28 | + return tryParse(cookieVal, enableParseJSON) |
| 29 | + } |
| 30 | + |
| 31 | + const cookie = ref(getCookie()) |
| 32 | + |
| 33 | + const updateCookie = ( |
| 34 | + newVal: CookieValueType, |
| 35 | + options?: Cookies.CookieAttributes |
| 36 | + ) => { |
| 37 | + const newCookieValue = tryStringify(newVal, enableParseJSON) |
| 38 | + Cookies.set(cookieName, newCookieValue, options) |
| 39 | + cookie.value = newVal |
| 40 | + } |
| 41 | + |
| 42 | + const deleteCookie = (options?: Cookies.CookieAttributes) => { |
| 43 | + Cookies.remove(cookieName, options) |
| 44 | + cookie.value = null |
| 45 | + } |
| 46 | + |
| 47 | + return { cookie, updateCookie, deleteCookie } |
| 48 | +} |
0 commit comments