-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
42 lines (37 loc) · 1.2 KB
/
Copy pathindex.ts
File metadata and controls
42 lines (37 loc) · 1.2 KB
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
39
40
41
42
const namespaces: Record<string, Record<string, unknown>> = {}
export const ns = <T extends object>(
name: string,
props: T,
options?: {
before?: (props?: T) => Promise<unknown>
after?: (props: T) => Promise<unknown>
forceRewrite?: boolean
rewriteKeys?: (keyof T)[]
sync?: boolean
}
) => {
const core = () => {
const rewriteKeysIdx: Record<string, boolean> = {}
options?.rewriteKeys?.forEach(k => (rewriteKeysIdx[k as string] = true))
namespaces[name] ??= {}
const entries = Object.entries(props)
const newEntries = entries.filter(
([key, value]) =>
options?.forceRewrite || rewriteKeysIdx[key] || typeof value === 'function' || namespaces[name]![key] == null
)
Object.assign(namespaces[name]!, Object.fromEntries(newEntries))
}
const ready = options?.sync
? (() => {
options?.before?.(namespaces[name] as T)
core()
options?.after?.(namespaces[name] as T)
return Promise.resolve()
})()
: (async () => {
await options?.before?.(namespaces[name] as T)
core()
await options?.after?.(namespaces[name] as T)
})()
return Object.assign(() => namespaces[name] as T, { ready })
}