webapp/src/context/inbox.tsx

68 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-12-07 07:39:09 +00:00
import { Accessor, createMemo, JSX, onMount } from 'solid-js'
2022-11-30 15:25:02 +00:00
import { createContext, createSignal, useContext } from 'solid-js'
2022-12-07 07:39:09 +00:00
import { createChatClient } from '../graphql/privateGraphQLClient'
2022-11-30 15:25:02 +00:00
import type { Chat } from '../graphql/types.gen'
2022-11-24 15:39:31 +00:00
import { apiClient } from '../utils/apiClient'
2022-12-07 07:39:09 +00:00
import newMessages from '../graphql/subs/new-messages'
2022-12-07 12:47:43 +00:00
import type { Client } from '@urql/core'
import { pipe, subscribe } from 'wonka'
2022-11-24 15:39:31 +00:00
type InboxContextType = {
2022-11-30 15:25:02 +00:00
chats: Accessor<Chat[]>
2022-11-24 15:39:31 +00:00
actions: {
2022-12-07 06:10:45 +00:00
createChat: (members: number[], title: string) => Promise<{ chat: Chat }>
2022-11-30 15:25:02 +00:00
loadChats: () => Promise<void>
2022-12-07 07:39:09 +00:00
setListener: (listener: (ev) => void) => void
2022-11-24 15:39:31 +00:00
}
}
const InboxContext = createContext<InboxContextType>()
export function useInbox() {
return useContext(InboxContext)
}
export const InboxProvider = (props: { children: JSX.Element }) => {
2022-11-30 15:25:02 +00:00
const [chats, setChats] = createSignal<Chat[]>([])
2022-12-07 07:39:09 +00:00
const [listener, setListener] = createSignal(console.debug)
2022-12-07 12:47:43 +00:00
const subclient = createMemo<Client>(() => createChatClient(listener()))
2022-11-30 15:25:02 +00:00
const loadChats = async () => {
try {
2022-12-01 03:26:44 +00:00
const newChats = await apiClient.getChats({ limit: 50, offset: 0 })
2022-11-30 15:25:02 +00:00
setChats(
2022-12-01 03:26:44 +00:00
newChats.sort((x, y) => {
2022-11-30 15:25:02 +00:00
return x.updatedAt < y.updatedAt ? 1 : -1
})
)
} catch (error) {
console.log(error)
}
}
2022-11-24 15:39:31 +00:00
2022-12-03 14:34:15 +00:00
const createChat = async (members: number[], title: string) => {
2022-11-27 05:49:48 +00:00
const chat = await apiClient.createChat({ members, title })
2022-11-30 15:25:02 +00:00
setChats((prevChats) => {
return [chat, ...prevChats]
2022-11-25 07:36:45 +00:00
})
2022-11-25 23:34:46 +00:00
return chat
2022-11-24 15:39:31 +00:00
}
const actions = {
2022-11-30 15:25:02 +00:00
createChat,
2022-12-07 07:39:09 +00:00
loadChats,
setListener // setting listening handler
2022-11-24 15:39:31 +00:00
}
2022-12-07 12:47:43 +00:00
onMount(async () => {
const { unsubscribe } = pipe(
subclient().subscription(newMessages, {}),
subscribe((result) => {
console.debug(result) // { data: ... }
// TODO: handle data result
})
)
2022-12-07 07:39:09 +00:00
})
2022-11-30 15:25:02 +00:00
const value: InboxContextType = { chats, actions }
2022-11-24 15:39:31 +00:00
return <InboxContext.Provider value={value}>{props.children}</InboxContext.Provider>
}