forked from vitest-dev/vitest
/
ssr-handlers.ts
38 lines (32 loc) · 1.43 KB
/
ssr-handlers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import type { Awaitable } from '@vueuse/shared'
export interface StorageLikeAsync {
getItem(key: string): Awaitable<string | null>
setItem(key: string, value: string): Awaitable<void>
removeItem(key: string): Awaitable<void>
}
export interface StorageLike {
getItem(key: string): string | null
setItem(key: string, value: string): void
removeItem(key: string): void
}
/**
* @expiremental The API is not finalized yet. It might not follow semver.
*/
export interface SSRHandlersMap {
getDefaultStorage: () => StorageLike | undefined
getDefaultStorageAsync: () => StorageLikeAsync | undefined
updateHTMLAttrs: (selector: string, attribute: string, value: string) => void
}
const globalKey = '__vueuse_ssr_handlers__'
// @ts-expect-error
globalThis[globalKey] = globalThis[globalKey] || {}
// @ts-expect-error
const handlers: Partial<SSRHandlersMap> = globalThis[globalKey]
export function getSSRHandler<T extends keyof SSRHandlersMap>(key: T, fallback: SSRHandlersMap[T]): SSRHandlersMap[T]
export function getSSRHandler<T extends keyof SSRHandlersMap>(key: T, fallback: SSRHandlersMap[T] | undefined): SSRHandlersMap[T] | undefined
export function getSSRHandler<T extends keyof SSRHandlersMap>(key: T, fallback?: SSRHandlersMap[T]): SSRHandlersMap[T] | undefined {
return handlers[key] as SSRHandlersMap[T] || fallback
}
export function setSSRHandler<T extends keyof SSRHandlersMap>(key: T, fn: SSRHandlersMap[T]) {
handlers[key] = fn
}