feat: chat layer tracer: bootstrap, channel list, messages, composer
- 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}
This commit is contained in:
72
app/composables/useChat.ts
Normal file
72
app/composables/useChat.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
// The chat store: membership, channels, the open conversation, messages and
|
||||
// drafts, as useState keys prefixed chat: (no Pinia). Every component that
|
||||
// calls useChat() shares the same state.
|
||||
import type { ChatChannel, ChatMessage } from '../lib/types'
|
||||
|
||||
/** The fallback page size of the message list. */
|
||||
export const MESSAGE_PAGE = 50
|
||||
|
||||
export function useChat() {
|
||||
const api = useChatApi()
|
||||
const config = useChatConfig()
|
||||
|
||||
/** undefined: not known yet; false: outside the community. */
|
||||
const member = useState<boolean | undefined>('chat:member', () => undefined)
|
||||
const channels = useState<ChatChannel[]>('chat:channels', () => [])
|
||||
/** The open conversation id. */
|
||||
const activeId = useState<number | null>('chat:activeId', () => null)
|
||||
const messages = useState<Record<number, ChatMessage[]>>('chat:messages', () => ({}))
|
||||
const drafts = useState<Record<number, string>>('chat:drafts', () => ({}))
|
||||
const error = useState<string>('chat:error', () => '')
|
||||
const sending = useState<boolean>('chat:sending', () => false)
|
||||
|
||||
/** Loads the bootstrap; without public.chat.hostApiBase it logs an error and stops. */
|
||||
async function start(): Promise<void> {
|
||||
if (!config.hostApiBase) {
|
||||
console.error('vue-chat-layer: runtimeConfig.public.chat.hostApiBase is not set; the chat does not start')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const b = await api.bootstrap()
|
||||
if (!b.member) {
|
||||
member.value = false
|
||||
channels.value = []
|
||||
return
|
||||
}
|
||||
member.value = true
|
||||
channels.value = b.channels.map((c) => ({ ...c }))
|
||||
} catch {
|
||||
error.value = 'bootstrap'
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens a channel: the conversation route joins it, then the latest page loads. */
|
||||
async function open(channel: ChatChannel): Promise<void> {
|
||||
error.value = ''
|
||||
await api.openConversation('channel', channel.id)
|
||||
activeId.value = channel.conversation_id
|
||||
messages.value[channel.conversation_id] = await api.messages(channel.conversation_id, { limit: MESSAGE_PAGE })
|
||||
}
|
||||
|
||||
/** Sends text to the open conversation; the message appears once the API answers. */
|
||||
async function send(text: string): Promise<boolean> {
|
||||
const id = activeId.value
|
||||
const content = text.trim()
|
||||
if (id === null || !content || sending.value) return false
|
||||
sending.value = true
|
||||
try {
|
||||
const m = await api.send(id, { content })
|
||||
const list = messages.value[id] ?? (messages.value[id] = [])
|
||||
if (!list.some((x) => x.id === m.id)) list.push(m)
|
||||
drafts.value[id] = ''
|
||||
return true
|
||||
} catch {
|
||||
error.value = 'send'
|
||||
return false
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
return { member, channels, activeId, messages, drafts, error, sending, start, open, send }
|
||||
}
|
||||
56
app/composables/useChatApi.ts
Normal file
56
app/composables/useChatApi.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
// 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
|
||||
}
|
||||
Reference in New Issue
Block a user