Skip to content

Commit 61f32f2

Browse files
committed
chore: split kv & config
1 parent 77e6800 commit 61f32f2

File tree

3 files changed

+50
-3
lines changed

3 files changed

+50
-3
lines changed

_nuxthub/modules/hub/index.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ const DEFAULT_WRANGLER = `d1_databases = [
5959
{ binding = "DB", database_name = "default", database_id = "default" },
6060
]
6161
kv_namespaces = [
62-
{ binding = "KV", id = "default" },
62+
{ binding = "KV", id = "user_default" },
63+
{ binding = "CONFIG", id = "config_default" },
6364
]
6465
r2_buckets = [
6566
{ binding = "BLOB", bucket_name = "default" },
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { createH3StorageHandler } from 'unstorage/server'
2+
3+
export default eventHandler(async (event) => {
4+
const storage = useConfigKV()
5+
return createH3StorageHandler(storage, {
6+
resolvePath(event) {
7+
return event.context.params!.path || ''
8+
}
9+
})(event)
10+
})

_nuxthub/server/utils/config.ts

+38-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1+
import type { Storage } from 'unstorage'
12
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'
27

38
const defaults: Config = {
49
oauth: {
@@ -14,10 +19,41 @@ const defaults: Config = {
1419
}
1520
}
1621

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+
1753
let _config: Config
1854

1955
export async function _fetchConfig() {
20-
let configValue = await useKV().getItem<Config>('_config')
56+
let configValue = await useConfigKV().getItem<Config>('config')
2157
configValue = z.custom<Config>().parse(configValue)
2258
_config = defu(configValue, defaults)
2359

@@ -39,7 +75,7 @@ export async function setConfig(config: Config) {
3975

4076
let configValue = z.custom<Config>().parse(config)
4177
configValue = defu(config, _config)
42-
await useKV().setItem('_config', configValue)
78+
await useConfigKV().setItem('config', configValue)
4379
_config = configValue
4480

4581
return _config

0 commit comments

Comments
 (0)