1
+ import type { Storage } from 'unstorage'
1
2
import { defu } from 'defu'
3
+ import { createStorage } from 'unstorage'
4
+ import httpDriver from 'unstorage/drivers/http'
5
+ import cloudflareKVBindingDriver from 'unstorage/drivers/cloudflare-kv-binding'
6
+ import { joinURL } from 'ufo'
2
7
3
8
const defaults : Config = {
4
9
oauth : {
@@ -14,10 +19,41 @@ const defaults: Config = {
14
19
}
15
20
}
16
21
22
+ let _configKV : Storage
23
+
24
+ export function useConfigKV ( ) {
25
+ if ( ! _configKV ) {
26
+ if ( import . meta. dev && process . env . NUXT_HUB_URL ) {
27
+ // Use https://unstorage.unjs.io/drivers/http
28
+ _configKV = createStorage ( {
29
+ driver : httpDriver ( {
30
+ base : joinURL ( process . env . NUXT_HUB_URL , '/api/_hub/config/' ) ,
31
+ headers : {
32
+ Authorization : `Bearer ${ process . env . NUXT_HUB_SECRET_KEY } `
33
+ }
34
+ } )
35
+ } )
36
+ } else {
37
+ const binding = process . env . CONFIG || globalThis . __env__ ?. CONFIG || globalThis . CONFIG
38
+ if ( binding ) {
39
+ _configKV = createStorage ( {
40
+ driver : cloudflareKVBindingDriver ( {
41
+ binding
42
+ } )
43
+ } )
44
+ } else {
45
+ throw createError ( 'Missing Cloudflare binding CONFIG' )
46
+ }
47
+ }
48
+ }
49
+
50
+ return _configKV
51
+ }
52
+
17
53
let _config : Config
18
54
19
55
export async function _fetchConfig ( ) {
20
- let configValue = await useKV ( ) . getItem < Config > ( '_config ' )
56
+ let configValue = await useConfigKV ( ) . getItem < Config > ( 'config ' )
21
57
configValue = z . custom < Config > ( ) . parse ( configValue )
22
58
_config = defu ( configValue , defaults )
23
59
@@ -39,7 +75,7 @@ export async function setConfig(config: Config) {
39
75
40
76
let configValue = z . custom < Config > ( ) . parse ( config )
41
77
configValue = defu ( config , _config )
42
- await useKV ( ) . setItem ( '_config ' , configValue )
78
+ await useConfigKV ( ) . setItem ( 'config ' , configValue )
43
79
_config = configValue
44
80
45
81
return _config
0 commit comments