feat(useCookie): support default value (#2147)

This commit is contained in:
Anthony Fu 2021-11-29 18:40:12 +08:00 committed by GitHub
parent f3082ca601
commit 010febd1b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -7,9 +7,11 @@ import destr from 'destr'
import { useNuxtApp } from '#app'
type _CookieOptions = Omit<CookieSerializeOptions & CookieParseOptions, 'decode' | 'encode'>
export interface CookieOptions<T=any> extends _CookieOptions {
decode?(value: string): T
encode?(value: T): string;
default?: () => T
}
export interface CookieRef<T> extends Ref<T> {}
@ -23,10 +25,10 @@ export function useCookie <T=string> (name: string, _opts?: CookieOptions<T>): C
const opts = { ...CookieDefaults, ..._opts }
const cookies = readRawCookies(opts)
const cookie = ref(cookies[name])
const cookie = ref(cookies[name] ?? _opts.default?.())
if (process.client) {
watch(cookie, () => { writeClientCookie(name, cookie.value, opts) })
watch(cookie, () => { writeClientCookie(name, cookie.value, opts as CookieSerializeOptions) })
} else if (process.server) {
const initialValue = cookie.value
const nuxtApp = useNuxtApp()
@ -38,7 +40,7 @@ export function useCookie <T=string> (name: string, _opts?: CookieOptions<T>): C
})
}
return cookie
return cookie as CookieRef<T>
}
// @ts-ignore
@ -70,7 +72,7 @@ function writeClientCookie (name: string, value: any, opts: CookieSerializeOptio
function writeServerCookie (res: ServerResponse, name: string, value: any, opts: CookieSerializeOptions = {}) {
if (res) {
// TODO: Try to smart join with exisiting Set-Cookie headers
// TODO: Try to smart join with existing Set-Cookie headers
appendHeader(res, 'Set-Cookie', serializeCookie(name, value, opts))
}
}