Skip to content

Commit

Permalink
chore: up
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux committed Feb 5, 2024
1 parent 61f32f2 commit acfbd4e
Show file tree
Hide file tree
Showing 10 changed files with 118 additions and 106 deletions.
3 changes: 0 additions & 3 deletions _nuxthub/composables/config.ts

This file was deleted.

7 changes: 7 additions & 0 deletions _nuxthub/composables/hub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function useHub() {
const config = useState<HubConfig['public']>('hub_config')

return {
config
}
}
2 changes: 1 addition & 1 deletion _nuxthub/plugins/config.server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export default defineNuxtPlugin(() => {
const event = useRequestEvent()

useState('hub_config', () => event?.context.config?.public || {})
useState('hub_config', () => event?.context.hub?.config?.public || {})
})
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ export default eventHandler(async event => {
throw createError({ statusCode: 400, message: 'Could not resolve this provider.' })
}

// TODO: handle redirect with ?redirect query param (must start with /)
return oauth[handlerName as OAuthHandler]({
config: oauthConfig as any,
async onSuccess(event, { user }) {
// TODO: handle user creation in database with provider
await setUserSession(event, { user })
return sendRedirect(event, '/todos')
return sendRedirect(event, config.oauth.redirect)
}
})(event)
})
6 changes: 5 additions & 1 deletion _nuxthub/server/middleware/1.config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
export default eventHandler(async (event) => {
event.context.config = await _fetchConfig()
const config = await _fetchConfig(event)

event.context.hub = {
config
}
})
85 changes: 42 additions & 43 deletions _nuxthub/server/utils/config.ts
Original file line number Diff line number Diff line change
@@ -1,61 +1,60 @@
import type { H3Event } from 'h3'
import type { Storage } from 'unstorage'
import { defu } from 'defu'
import { createStorage } from 'unstorage'
import httpDriver from 'unstorage/drivers/http'
import cloudflareKVBindingDriver from 'unstorage/drivers/cloudflare-kv-binding'
import { joinURL } from 'ufo'

const defaults: Config = {
oauth: {
github: {
clientId: process.env.NUXT_OAUTH_GITHUB_CLIENT_ID,
clientSecret: process.env.NUXT_OAUTH_GITHUB_CLIENT_SECRET
}
},
public: {
features: {
// users features
}
}
}

let _configKV: Storage

export function useConfigKV () {
if (!_configKV) {
if (import.meta.dev && process.env.NUXT_HUB_URL) {
// Use https://unstorage.unjs.io/drivers/http
_configKV = createStorage({
driver: httpDriver({
base: joinURL(process.env.NUXT_HUB_URL, '/api/_hub/config/'),
headers: {
Authorization: `Bearer ${process.env.NUXT_HUB_SECRET_KEY}`
}
})
if (_configKV) {
return _configKV
}
if (import.meta.dev && process.env.NUXT_HUB_URL) {
// Use https://unstorage.unjs.io/drivers/http
_configKV = createStorage({
driver: httpDriver({
base: joinURL(process.env.NUXT_HUB_URL, '/api/_hub/config/'),
headers: {
Authorization: `Bearer ${process.env.NUXT_HUB_SECRET_KEY}`
}
})
} else {
const binding = process.env.CONFIG || globalThis.__env__?.CONFIG || globalThis.CONFIG
if (binding) {
_configKV = createStorage({
driver: cloudflareKVBindingDriver({
binding
})
})
} else {
throw createError('Missing Cloudflare binding CONFIG')
}
}
})
return _configKV
}
// @ts-ignore
const binding = process.env.CONFIG || globalThis.__env__?.CONFIG || globalThis.CONFIG
if (!binding) {
throw createError('Missing Cloudflare binding CONFIG')
}
_configKV = createStorage({
driver: cloudflareKVBindingDriver({
binding
})
})

return _configKV
}

let _config: Config
let _config: HubConfig

export async function _fetchConfig() {
let configValue = await useConfigKV().getItem<Config>('config')
configValue = z.custom<Config>().parse(configValue)
_config = defu(configValue, defaults)
export async function _fetchConfig(event: H3Event) {
const runtimeConfig = useRuntimeConfig(event)
let configValue = await useConfigKV().getItem<HubConfig>('config')
configValue = z.custom<HubConfig>().parse(configValue)
_config = defu(configValue, {
oauth: {
redirect: '/',
...runtimeConfig.oauth
},
public: {
features: {
// users features
}
}
} as HubConfig)

return _config
}
Expand All @@ -68,12 +67,12 @@ export function getConfig() {
return _config
}

export async function setConfig(config: Config) {
export async function setConfig(config: HubConfig) {
if (!_config) {
throw createError('Please run _fetchConfig() in order to use setConfig()')
}

let configValue = z.custom<Config>().parse(config)
let configValue = z.custom<HubConfig>().parse(config)
configValue = defu(config, _config)
await useConfigKV().setItem('config', configValue)
_config = configValue
Expand Down
57 changes: 29 additions & 28 deletions _nuxthub/server/utils/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,38 +14,39 @@ let _db: DrizzleD1Database | BetterSQLite3Database | SqliteRemoteDatabase
let _client: D1Database

export function useDatabase () {
if (!_db) {
if (import.meta.dev && process.env.NUXT_HUB_URL) {
_db = drizzleHTTP(async (sql, params, method) => {
// https://orm.drizzle.team/docs/get-started-sqlite#http-proxy
try {
const rows = await ofetch('/api/_hub/database/query', {
baseURL: process.env.NUXT_HUB_URL,
method: 'POST',
body: { sql, params, method },
headers: {
Authorization: `Bearer ${process.env.NUXT_HUB_SECRET_KEY}`
}
})
if (method === 'run') return rows
return { rows }
} catch (err: any) {
if (['begin', 'commit'].includes(sql)) {
return { rows: [] }
if (_db) {
return _db
}
if (import.meta.dev && process.env.NUXT_HUB_URL) {
_db = drizzleHTTP(async (sql, params, method) => {
// https://orm.drizzle.team/docs/get-started-sqlite#http-proxy
try {
const rows = await ofetch('/api/_hub/database/query', {
baseURL: process.env.NUXT_HUB_URL,
method: 'POST',
body: { sql, params, method },
headers: {
Authorization: `Bearer ${process.env.NUXT_HUB_SECRET_KEY}`
}
console.error('Error from remote database:', err.data.message, '\n', { sql, params, method })
})
if (method === 'run') return rows
return { rows }
} catch (err: any) {
if (['begin', 'commit'].includes(sql)) {
return { rows: [] }
}
})
} else {
const binding = process.env.DB || globalThis.__env__?.DB || globalThis.DB
if (binding) {
_client = binding as D1Database
_db = drizzleD1(_client)
} else {
throw createError('Missing Cloudflare D1 binding DB')
console.error('Error from remote database:', err.data.message, '\n', { sql, params, method })
return { rows: [] }
}
}
})
return _db
}
const binding = process.env.DB || globalThis.__env__?.DB || globalThis.DB
if (binding) {
_client = binding as D1Database
_db = drizzleD1(_client)
} else {
throw createError('Missing Cloudflare D1 binding DB')
}
return _db
}
Expand Down
46 changes: 23 additions & 23 deletions _nuxthub/server/utils/kv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,30 @@ import { joinURL } from 'ufo'
let _kv: Storage

export function useKV () {
if (!_kv) {
if (import.meta.dev && process.env.NUXT_HUB_URL) {
// Use https://unstorage.unjs.io/drivers/http
_kv = createStorage({
driver: httpDriver({
base: joinURL(process.env.NUXT_HUB_URL, '/api/_hub/kv/'),
headers: {
Authorization: `Bearer ${process.env.NUXT_HUB_SECRET_KEY}`
}
})
if (_kv) {
return _kv
}
if (import.meta.dev && process.env.NUXT_HUB_URL) {
// Use https://unstorage.unjs.io/drivers/http
_kv = createStorage({
driver: httpDriver({
base: joinURL(process.env.NUXT_HUB_URL, '/api/_hub/kv/'),
headers: {
Authorization: `Bearer ${process.env.NUXT_HUB_SECRET_KEY}`
}
})
} else {
const binding = process.env.KV || globalThis.__env__?.KV || globalThis.KV
if (binding) {
_kv = createStorage({
driver: cloudflareKVBindingDriver({
binding
})
})
} else {
throw createError('Missing Cloudflare binding KV')
}
}
})
return _kv
}
const binding = process.env.KV || globalThis.__env__?.KV || globalThis.KV
if (binding) {
_kv = createStorage({
driver: cloudflareKVBindingDriver({
binding
})
})
} else {
throw createError('Missing Cloudflare binding KV')
}

return _kv
}
12 changes: 7 additions & 5 deletions _nuxthub/types/config.d.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
declare interface Config {
oauth?: {
declare interface HubConfig {
oauth: {
redirect: string
[key: string]: {
clientId?: string
clientSecret?: string
}
},
public?: {
features?: object
}
/**
* Configuration exposed to the Vue part
*/
public: {}
}
2 changes: 1 addition & 1 deletion pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const { loggedIn } = useUserSession()
</h3>
<UButton
v-if="!loggedIn"
to="/api/auth/github"
to="/api/auth/providers/github"
icon="i-simple-icons-github"
label="Login with GitHub"
color="black"
Expand Down

0 comments on commit acfbd4e

Please sign in to comment.