@orpc/vue-query
Version:
<div align="center"> <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" /> </div>
96 lines (89 loc) • 2.77 kB
JavaScript
import { isRef, computed } from 'vue';
import { isObject } from '@orpc/shared';
function buildKey(path, options) {
const withInput = options?.input !== void 0 ? { input: options?.input } : {};
const withType = options?.type !== void 0 ? { type: options?.type } : {};
return [path, {
...withInput,
...withType
}];
}
function createGeneralUtils(path) {
return {
key(options) {
return buildKey(path, options);
}
};
}
function unrefDeep(value) {
if (isRef(value)) {
return unrefDeep(value.value);
}
if (Array.isArray(value)) {
return value.map(unrefDeep);
}
if (isObject(value)) {
return Object.keys(value).reduce((acc, key) => {
acc[key] = unrefDeep(value[key]);
return acc;
}, {});
}
return value;
}
function createProcedureUtils(client, options) {
return {
call: client,
queryOptions(...[optionsIn = {}]) {
return {
queryKey: computed(() => buildKey(options.path, { type: "query", input: unrefDeep(optionsIn.input) })),
queryFn: ({ signal }) => client(unrefDeep(optionsIn.input), { signal, context: unrefDeep(optionsIn.context) }),
...optionsIn
};
},
infiniteOptions(optionsIn) {
return {
queryKey: computed(() => {
return buildKey(options.path, { type: "infinite", input: unrefDeep(optionsIn.input(unrefDeep(optionsIn.initialPageParam))) });
}),
queryFn: ({ pageParam, signal }) => {
return client(unrefDeep(optionsIn.input(pageParam)), { signal, context: unrefDeep(optionsIn.context) });
},
...optionsIn
};
},
mutationOptions(...[optionsIn = {}]) {
return {
mutationKey: buildKey(options.path, { type: "mutation" }),
mutationFn: (input) => client(input, { context: unrefDeep(optionsIn.context) }),
...optionsIn
};
}
};
}
function createRouterUtils(client, options = {}) {
const path = options.path ?? [];
const generalUtils = createGeneralUtils(path);
const procedureUtils = createProcedureUtils(client, { path });
const recursive = new Proxy({
...generalUtils,
...procedureUtils
}, {
get(target, prop) {
const value = Reflect.get(target, prop);
if (typeof prop !== "string") {
return value;
}
const nextUtils = createRouterUtils(client[prop], { ...options, path: [...path, prop] });
if (typeof value !== "function") {
return nextUtils;
}
return new Proxy(value, {
get(_, prop2) {
return Reflect.get(nextUtils, prop2);
}
});
}
});
return recursive;
}
export { buildKey, createGeneralUtils, createRouterUtils as createORPCVueQueryUtils, createProcedureUtils, createRouterUtils, unrefDeep };