Skip to content

Commit

Permalink
feat(useSurrealWS): unwrap rpc response by default
Browse files Browse the repository at this point in the history
  • Loading branch information
sandros94 committed Jun 13, 2024
1 parent b6ab76a commit bacbccd
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions src/runtime/composables/surreal-ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,18 @@ import {

type MROGParam<T, M extends keyof RpcMethodsWS<T>, N extends number> = MaybeRefOrGetter<RpcParamsWS<T, M>[N]>

export function useSurrealWS<T = any>(
export function useSurrealWS(
options?: UseWebSocketOptions & {
database?: Overrides['database']
auth?: string | null | false
},
) {
const { databases, defaultDatabase, auth: { database: authDatabase } } = useRuntimeConfig().public.surrealdb
const {
auth: { database: authDatabase },
databases,
defaultDatabase,
unwrapRpcResponse,
} = useRuntimeConfig().public.surrealdb
const { token: userAuth } = useSurrealAuth()

const { database, onDisconnected: _onDisconnected, ...opts } = options || {}
Expand Down Expand Up @@ -65,20 +70,21 @@ export function useSurrealWS<T = any>(
send: _send,
status,
ws,
} = useWebSocket<RpcResponseWS<T>>(joinURL(_database.value.ws!, 'rpc'), {
} = useWebSocket<string>(joinURL(_database.value.ws!, 'rpc'), {
onDisconnected(ws, event) {
idCounter.value = 0
_onDisconnected?.(ws, event)
},
...opts,
})

const data = computed(() => destr<RpcResponseWS<any> | null>(_data.value))
const stopInitWatcher = watch(data, (newData) => {
if (newData && newData.id === useId) {
const stopInitWatcher = watch(_data, (newData) => {
const _newData = destr<RpcResponseWS<any> | null>(newData)
if (_newData && _newData.id === useId) {
isReady.db = true
console.log(typeof _data.value, _data.value)
}
else if (newData && newData.id === authId) {
else if (_newData && _newData.id === authId) {
isReady.auth = true
_sendQueue()
stopInitWatcher()
Expand Down Expand Up @@ -118,6 +124,16 @@ export function useSurrealWS<T = any>(
}
}

const data = computed(() => {
const res = destr<RpcResponseWS<any> | null>(_data.value)
if (unwrapRpcResponse && !res?.error) {
return res?.result
}
else {
return res
}
})

function send(data: Record<string, any>, useBuffer = true) {
if (!isReady.db || (isAuthDatabase && !isReady.auth)) {
queue.push(data)
Expand Down

0 comments on commit bacbccd

Please sign in to comment.