UNPKG

@falcondev-oss/trpc-vue-query

Version:
69 lines (68 loc) 2.27 kB
// src/index.ts import { useMutation, useQuery } from "@tanstack/vue-query"; import { createTRPCProxyClient } from "@trpc/client"; import { createFlatProxy, createRecursiveProxy } from "@trpc/server/shared"; import { toRef, toRefs, toValue } from "@vueuse/core"; import { computed, isReactive } from "vue"; function getQueryKey(path, input) { return input === void 0 ? path : [...path, input]; } function maybeToRefs(obj) { return isReactive(obj) ? toRefs(obj) : toRefs(toRef(obj)); } function createVueQueryProxyDecoration(name, client, queryClient) { return createRecursiveProxy((opts) => { const args = opts.args; const path = [name, ...opts.path]; const lastProperty = path.pop(); const joinedPath = path.join("."); const [firstParam, secondParam] = args; if (lastProperty === "_def") { return { path }; } if (lastProperty === "useQuery") { const { trpc, ...queryOptions } = secondParam || {}; return useQuery({ queryKey: computed(() => getQueryKey(path, toValue(firstParam))), queryFn: ({ queryKey, signal }) => client[joinedPath].query(queryKey.at(-1), { signal, ...trpc }), ...maybeToRefs(queryOptions) }); } if (lastProperty === "invalidate") { return queryClient.invalidateQueries({ queryKey: getQueryKey(path, toValue(firstParam)) }); } if (lastProperty === "setQueryData") { return queryClient.setQueryData(getQueryKey(path, toValue(secondParam)), firstParam); } if (lastProperty === "key") { return getQueryKey(path, toValue(firstParam)); } if (lastProperty === "useMutation") { const { trpc, ...mutationOptions } = firstParam || {}; return useMutation({ mutationFn: (payload) => client[joinedPath].mutate(payload, { ...trpc }), ...maybeToRefs(mutationOptions) }); } return client[joinedPath][lastProperty](...args); }); } function createTRPCVueQueryClient(opts) { const client = createTRPCProxyClient(opts.trpc); const decoratedClient = createFlatProxy((key) => { return createVueQueryProxyDecoration(key, client, opts.queryClient); }); return decoratedClient; } export { createTRPCVueQueryClient };