elk/server/shared.ts

67 lines
1.9 KiB
TypeScript
Raw Normal View History

// @ts-expect-error unstorage needs to provide backwards-compatible subpath types
import _fs from 'unstorage/drivers/fs'
// @ts-expect-error unstorage needs to provide backwards-compatible subpath types
import _kv from 'unstorage/drivers/cloudflare-kv-http'
import { parseURL } from 'ufo'
2022-11-15 17:29:46 +03:00
import { $fetch } from 'ohmyfetch'
import type { Storage } from 'unstorage'
2022-11-30 01:45:07 +03:00
import { isCI } from 'std-env'
import cached from './cache-driver'
2022-11-15 18:48:23 +03:00
import type { AppInfo } from '~/types'
import { APP_NAME } from '~/constants'
2022-11-15 17:29:46 +03:00
2022-11-27 21:39:40 +03:00
const config = useRuntimeConfig()
export const HOST_URL = config.deployUrl
export const HOST_DOMAIN = parseURL(HOST_URL).host!
const fs = _fs as typeof import('unstorage/dist/drivers/fs')['default']
const kv = _kv as typeof import('unstorage/dist/drivers/cloudflare-kv-http')['default']
2022-11-15 17:29:46 +03:00
const storage = useStorage() as Storage
2022-11-27 21:39:40 +03:00
if (config.env === 'local') {
storage.mount('servers', fs({ base: 'node_modules/.cache/servers' }))
}
else {
storage.mount('servers', cached(kv({
accountId: config.cloudflare.accountId,
namespaceId: config.cloudflare.namespaceId,
apiToken: config.cloudflare.apiToken,
})))
}
async function fetchAppInfo(server: string) {
const redirect_uris = [
'urn:ietf:wg:oauth:2.0:oob',
`${HOST_URL}/api/${server}/oauth`,
].join('\n')
const app: AppInfo = await $fetch(`https://${server}/api/v1/apps`, {
method: 'POST',
body: {
2022-11-30 01:45:07 +03:00
client_name: APP_NAME + (isCI ? '' : ' (dev)'),
redirect_uris,
scopes: 'read write follow push',
},
2022-11-15 18:48:23 +03:00
})
return app
}
2022-11-27 21:33:19 +03:00
export async function getApp(server: string) {
const key = `servers:${HOST_DOMAIN.replace(/[^\w\d]/g, '-')}:${server}.json`
try {
if (await storage.hasItem(key))
return await storage.getItem(key) as Promise<AppInfo>
const appInfo = await fetchAppInfo(server)
await storage.setItem(key, appInfo)
return appInfo
}
catch {
return null
}
2022-11-15 17:29:46 +03:00
}