Skip to content

Commit

Permalink
🔨 overload in ts & avoid assertion
Browse files Browse the repository at this point in the history
It appears to be repeating itself, but in reality, one is taking CookieOptions<T> & {readonly: true;} as input and returning Readonly<CookieRef<T>>, while the other is taking CookieOptions<T> & {readonly: true;} as input and returning CookieRef<T>. This way, it aligns with the appropriate overload call pattern.
  • Loading branch information
AuroraTea committed Mar 20, 2024
1 parent a6f47da commit ec0f1ba
Showing 1 changed file with 26 additions and 13 deletions.
39 changes: 26 additions & 13 deletions packages/nuxt/src/runtime/storages.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,39 @@
import type { StorageLike } from 'pinia-plugin-persistedstate'
import { type CookieOptions, useCookie, useNuxtApp } from '#app'

function usePersistedstateCookies(cookieOptions?: Omit<CookieOptions<string>, 'encode' | 'decode'>) {
function usePersistedstateCookies(
cookieOptions?: Omit<CookieOptions<string>, 'encode' | 'decode'>,
): StorageLike {
return ({
getItem: (key) => {
return useCookie<string>(key, {
...cookieOptions,
encode: encodeURIComponent,
decode: decodeURIComponent,
}).value
},
getItem: key =>
cookieOptions?.readonly
? useCookie<string>(key, {
...cookieOptions,
encode: encodeURIComponent,
decode: decodeURIComponent,
readonly: true,
}).value
: useCookie<string>(key, {
...cookieOptions,
encode: encodeURIComponent,
decode: decodeURIComponent,
readonly: false,
}).value,
setItem: (key, value) => {
if (cookieOptions?.readonly)
throw new Error('Cannot set a readonly cookie.')

useCookie<string>(key, {
...cookieOptions,
encode: encodeURIComponent,
decode: decodeURIComponent,
readonly: false,
}).value = value
},
}) as StorageLike
})
}

function usePersistedstateLocalStorage() {
function usePersistedstateLocalStorage(): StorageLike {
return ({
getItem: (key) => {
return !useNuxtApp().ssrContext
Expand All @@ -31,10 +44,10 @@ function usePersistedstateLocalStorage() {
if (!useNuxtApp().ssrContext)
localStorage.setItem(key, value)
},
}) as StorageLike
})
}

function usePersistedstateSessionStorage() {
function usePersistedstateSessionStorage(): StorageLike {
return ({
getItem: (key) => {
return !useNuxtApp().ssrContext
Expand All @@ -45,7 +58,7 @@ function usePersistedstateSessionStorage() {
if (!useNuxtApp().ssrContext)
sessionStorage.setItem(key, value)
},
}) as StorageLike
})
}

export const persistedState = {
Expand Down

0 comments on commit ec0f1ba

Please sign in to comment.