Is useQuery abstraction possible? #136
-
Due to the nature of our backend, we make hundreds of queries to retrieve data. We use our own format, very similar to JSON-RPC protocol. All requests are sent by POST method, the request body is standardized. interface RequestBody {
method: string,
data: any
}
By parameters of the request, we determine the URL to which it will be sent, as well as standardize the creation of query keys and add the auth data. So I would like to consult on how to properly abstract over the useQuery function, so that a developer would only need to call a special function with standardized parameters and get the result without having to describe query and key independently. const { data, isLoading, error } = useRequest({
method: 'someMethod',
data: {}
}) Is this possible and how consistent is it with the principles of the Pinia Colada? How would you implement it, if so? // Simplified example, here should be url definition,
// unref refs, add authorization data, response validation with zod schema and so on
function makeQuery(body: RequestBody) {
return ({ signal }: { signal: AbortSignal }) => {
return $fetch(getURL(body), { signal, method: 'POST', body })
}
}
function useRequest(params: RequestBody) {
return useQuery({
key: makeKey(params), // Returns a getter based on the query parameters
query: makeQuery(params)
})
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
That approach should work. You can even use your own wrapper within defineQuery |
Beta Was this translation helpful? Give feedback.
That approach should work. You can even use your own wrapper within defineQuery