metacubexd/src/signals/request.ts

78 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-09-06 19:33:07 +08:00
import { createEventSignal } from '@solid-primitives/event-listener'
import { makePersisted } from '@solid-primitives/storage'
2023-09-06 19:33:07 +08:00
import { createReconnectingWS } from '@solid-primitives/websocket'
import ky from 'ky'
2023-09-06 19:33:07 +08:00
import { createMemo, createSignal } from 'solid-js'
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()
if (!e) {
return ky.create({})
}
const headers = new Headers()
if (e.secret) {
headers.set('Authorization', `Bearer ${e.secret}`)
}
return ky.create({
prefixUrl: e.url,
headers,
})
}
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
export const useWsRequest = <T>(
path: string,
queries: Record<string, string> = {},
) => {
const queryParams = new URLSearchParams(queries)
queryParams.set('token', secret() ?? '')
2023-09-06 19:33:07 +08:00
const ws = createReconnectingWS(
`${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)
})
}