- createChatClient: bearer auth, one refresh-and-retry on 401, 422 field errors
- useChat over useState: host bootstrap, open a channel, send
- ChatPage, ChatChannelList, ChatMessageList, ChatComposer
- runtime config chat.apiBase, public.chat.{apiBase,channelsApiBase,botsApiBase,hostApiBase}
57 lines
2.0 KiB
TypeScript
57 lines
2.0 KiB
TypeScript
// The chat API client for the layer's components, bound to runtime config
|
|
// and the app's auth hook. One client per Nuxt app, so concurrent 401s share
|
|
// one token refresh.
|
|
//
|
|
// The auth hook: the app provides `chatAuth` from a Nuxt plugin. token()
|
|
// answers the user's frontend JWT (or null); refresh() renews it and answers
|
|
// the new one (or null); unauthorized() signs the user out locally:
|
|
//
|
|
// export default defineNuxtPlugin(() => ({
|
|
// provide: {
|
|
// chatAuth: {
|
|
// token: () => useCookie('token').value ?? null,
|
|
// refresh: async () => { ... return newToken },
|
|
// unauthorized: () => { useCookie('token').value = null },
|
|
// },
|
|
// },
|
|
// }))
|
|
//
|
|
// The token is sent as `Authorization: Bearer` (never as a cookie). The
|
|
// bases are always runtime config, never request input.
|
|
|
|
import { createChatClient, type ChatAuth, type ChatClient } from '../lib/client'
|
|
|
|
interface ChatPublicConfig {
|
|
apiBase: string
|
|
channelsApiBase: string
|
|
botsApiBase: string
|
|
hostApiBase: string
|
|
}
|
|
|
|
const NO_AUTH: ChatAuth = { token: () => null }
|
|
|
|
/** The app's $chatAuth hook, or a hook without a token. */
|
|
export function useChatAuth(): ChatAuth {
|
|
const hook = (useNuxtApp() as unknown as { $chatAuth?: Partial<ChatAuth> }).$chatAuth
|
|
if (!hook || typeof hook.token !== 'function') return NO_AUTH
|
|
return hook as ChatAuth
|
|
}
|
|
|
|
/** The public chat config (public.chat). */
|
|
export function useChatConfig(): ChatPublicConfig {
|
|
return useRuntimeConfig().public.chat as unknown as ChatPublicConfig
|
|
}
|
|
|
|
export function useChatApi(): ChatClient {
|
|
const nuxtApp = useNuxtApp() as unknown as { _chatClient?: ChatClient }
|
|
if (nuxtApp._chatClient) return nuxtApp._chatClient
|
|
const cfg = useChatConfig()
|
|
const chatBase = import.meta.server ? (useRuntimeConfig().chat as { apiBase: string }).apiBase : cfg.apiBase
|
|
const client = createChatClient({
|
|
bases: { chat: chatBase, channels: cfg.channelsApiBase, bots: cfg.botsApiBase, host: cfg.hostApiBase },
|
|
auth: useChatAuth(),
|
|
})
|
|
nuxtApp._chatClient = client
|
|
return client
|
|
}
|