2023-09-06 19:33:07 +08:00
|
|
|
import { createEventSignal } from '@solid-primitives/event-listener'
|
2023-09-03 03:26:29 +08:00
|
|
|
import { makePersisted } from '@solid-primitives/storage'
|
2023-09-06 19:33:07 +08:00
|
|
|
import { createReconnectingWS } from '@solid-primitives/websocket'
|
2023-09-03 03:26:29 +08:00
|
|
|
import ky from 'ky'
|
2023-09-06 19:33:07 +08:00
|
|
|
import { createMemo, createSignal } from 'solid-js'
|
2023-09-03 03:26:29 +08:00
|
|
|
|
|
|
|
export const [selectedEndpoint, setSelectedEndpoint] = makePersisted(
|
|
|
|
createSignal(''),
|
|
|
|
{
|
|
|
|
name: 'selectedEndpoint',
|
|
|
|
storage: localStorage,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
export const [endpointList, setEndpointList] = makePersisted(
|
|
|
|
createSignal<
|
|
|
|
{
|
|
|
|
id: string
|
|
|
|
url: string
|
|
|
|
secret: string
|
|
|
|
}[]
|
|
|
|
>([]),
|
|
|
|
{ name: 'endpointList', storage: localStorage },
|
|
|
|
)
|
|
|
|
|
|
|
|
export const useRequest = () => {
|
|
|
|
const e = endpoint()
|
|
|
|
|
2023-09-13 15:26:40 +08:00
|
|
|
if (!e) {
|
|
|
|
return ky.create({})
|
|
|
|
}
|
|
|
|
|
|
|
|
const headers = new Headers()
|
|
|
|
|
|
|
|
if (e.secret) {
|
|
|
|
headers.set('Authorization', `Bearer ${e.secret}`)
|
|
|
|
}
|
|
|
|
|
2023-09-03 03:26:29 +08:00
|
|
|
return ky.create({
|
2023-09-13 15:26:40 +08:00
|
|
|
prefixUrl: e.url,
|
|
|
|
headers,
|
2023-09-03 03:26:29 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
export const endpoint = () =>
|
|
|
|
endpointList().find(({ id }) => id === selectedEndpoint())
|
|
|
|
|
|
|
|
export const secret = () => endpoint()?.secret
|
|
|
|
|
2023-09-06 18:56:57 +08:00
|
|
|
export const wsEndpointURL = () =>
|
2024-04-02 23:02:03 +08:00
|
|
|
new URL(endpoint()?.url ?? '').href.replace('http', 'ws')
|
2023-09-06 19:33:07 +08:00
|
|
|
|
2023-09-14 16:49:39 +08:00
|
|
|
export const useWsRequest = <T>(
|
|
|
|
path: string,
|
2023-09-17 15:41:20 +08:00
|
|
|
queries: Record<string, string> = {},
|
2023-09-14 16:49:39 +08:00
|
|
|
) => {
|
|
|
|
const queryParams = new URLSearchParams(queries)
|
|
|
|
queryParams.set('token', secret() ?? '')
|
|
|
|
|
2023-09-06 19:33:07 +08:00
|
|
|
const ws = createReconnectingWS(
|
2023-09-14 16:49:39 +08:00
|
|
|
`${wsEndpointURL()}/${path}?${queryParams.toString()}`,
|
2023-09-06 19:33:07 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
const event = createEventSignal<{
|
|
|
|
message: MessageEvent
|
|
|
|
}>(ws, 'message')
|
|
|
|
|
|
|
|
return createMemo<T | null>(() => {
|
|
|
|
const e = event()
|
|
|
|
|
|
|
|
if (!e) {
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
|
|
|
|
return JSON.parse(event()?.data)
|
|
|
|
})
|
|
|
|
}
|