Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add vue-query #65

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions client-vue-query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './dist/client-vue-query/index'
177 changes: 177 additions & 0 deletions docs/content/1.get-started/2.usage/3.simple-vue-query.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
---
title: Simple Vue Query
description: tRPC-Nuxt provides first class integration with tRPC.
---

# Simple Usage

## 1. Create a tRPC router

Initialize your tRPC backend using the `initTRPC` function and create your first router.

::code-group

```ts [server/trpc/trpc.ts]
/**
* This is your entry point to setup the root configuration for tRPC on the server.
* - `initTRPC` should only be used once per app.
* - We export only the functionality that we use so we can enforce which base procedures should be used
*
* Learn how to create protected base procedures and other things below:
* @see https://trpc.io/docs/v10/router
* @see https://trpc.io/docs/v10/procedures
*/
import { initTRPC } from '@trpc/server'

const t = initTRPC.create()

/**
* Unprotected procedure
**/
export const publicProcedure = t.procedure;

export const router = t.router;
export const middleware = t.middleware;
```

```ts [server/api/trpc/[trpc].ts]
/**
* This is the API-handler of your app that contains all your API routes.
* On a bigger app, you will probably want to split this file up into multiple files.
*/
import { createNuxtApiHandler } from 'trpc-nuxt'
import { publicProcedure, router } from '~/server/trpc/trpc'
import { z } from 'zod'

export const appRouter = router({
hello: publicProcedure
// This is the input schema of your procedure
.input(
z.object({
text: z.string().nullish(),
}),
)
.query(({ input }) => {
// This is what you're returning to your client
return {
greeting: `hello ${input?.text ?? 'world'}`,
}
}),
login: publicProcedure
// using zod schema to validate and infer input values
.input(
z.object({
name: z.string(),
})
)
.mutation(({ input }) => {
// Here some login stuff would happen
return {
user: {
name: input.name,
role: "ADMIN",
},
};
}),
})

// export only the type definition of the API
// None of the actual implementation is exposed to the client
export type AppRouter = typeof appRouter

// export API handler
export default createNuxtApiHandler({
router: appRouter,
createContext: () => ({}),
})
```

::

## 2. Create Vue Query and tRPC client plugin

Create a strongly-typed plugin using your API's type signature.

::code-group

```ts [plugins/1.vue-query.ts]
import type { DehydratedState, VueQueryPluginOptions } from "@tanstack/vue-query"
import { VueQueryPlugin, QueryClient, hydrate, dehydrate } from "@tanstack/vue-query"
// Nuxt 3 app aliases
import { useState } from "#app"

export default defineNuxtPlugin((nuxt) => {
const vueQueryState = useState<DehydratedState | null>("vue-query")

// Modify your Vue Query global settings here
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 5000 } },
});
const options: VueQueryPluginOptions = { queryClient }

nuxt.vueApp.use(VueQueryPlugin, options)

if (process.server) {
nuxt.hooks.hook("app:rendered", () => {
vueQueryState.value = dehydrate(queryClient)
});
}

if (process.client) {
nuxt.hooks.hook("app:created", () => {
hydrate(queryClient, vueQueryState.value)
});
}
})

```

```ts [plugins/2.client.ts]
import { createTRPCNuxtClient, httpBatchLink } from "trpc-nuxt/client-vue-query"
import type { AppRouter } from '~/server/api/trpc/[trpc]'

export default defineNuxtPlugin(() => {
/**
* createTRPCNuxtClient adds a `useQuery` composable
* built on top of `useAsyncData`.
*/
const client = createTRPCNuxtClient<AppRouter>({
links: [
httpBatchLink({
url: '/api/trpc',
}),
],
})

return {
provide: {
client,
},
}
})
```

::

## 3. Make an API request

```vue [pages/index.vue]
<script setup lang="ts">
const { $client } = useNuxtApp()

const { isLoading, isError, data, error } = $client.hello.useQuery({ text: 'client' })
const { mutateAsync, isLoading, isError, data, error } = $client.login.useMutation()

const handleLogin = async () => {
const person = await mutateAsync({ name: "John Doe" })
}

</script>

<template>
<div>
<p>{{ hello.data?.greeting }}</p>
<p><button @click="handleLogin">Login</button></p>
</div>
</template>
```
10 changes: 9 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,20 @@
"types": "./dist/client/index.d.ts",
"require": "./dist/client/index.cjs",
"import": "./dist/client/index.mjs"
},
"./client-vue-query": {
"types": "./dist/client-vue-query/index.d.ts",
"require": "./dist/client-vue-query/index.cjs",
"import": "./dist/client-vue-query/index.mjs"
}
},
"main": "./dist/index.mjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist",
"client.d.ts"
"client.d.ts",
"client-vue-query.d.ts"
],
"scripts": {
"dev": "concurrently \"pnpm build --watch\" \"pnpm --filter playground dev\"",
Expand All @@ -35,6 +41,7 @@
"update-deps": "taze -w && pnpm i"
},
"peerDependencies": {
"@tanstack/vue-query": "^4.22.0",
"@trpc/client": "^10.8.0",
"@trpc/server": "^10.8.0"
},
Expand All @@ -46,6 +53,7 @@
},
"devDependencies": {
"@nuxt/eslint-config": "^0.1.1",
"@tanstack/vue-query": "^4.22.0",
"@trpc/client": "^10.8.1",
"@trpc/server": "^10.8.1",
"bumpp": "^8.2.1",
Expand Down
32 changes: 32 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

File renamed without changes.
81 changes: 81 additions & 0 deletions src/client-vue-query/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { useQuery, useMutation } from "@tanstack/vue-query"
import {
type CreateTRPCClientOptions,
type inferRouterProxyClient,
createTRPCProxyClient,
} from "@trpc/client"
import { type AnyRouter } from "@trpc/server"
import { createFlatProxy, createRecursiveProxy } from "@trpc/server/shared"
import { type DecoratedProcedureRecord } from "./types"
// @ts-expect-error: Nuxt auto-imports
import { getCurrentInstance, onScopeDispose, useAsyncData } from "#imports"
import { getQueryKey } from "./internals/getQueryKey"
import { getArrayQueryKey } from "./internals/getArrayQueryKey"

export function getClientArgs<TPathAndInput extends unknown[], TOptions>(
pathAndInput: TPathAndInput,
opts: TOptions
) {
const [path, input] = pathAndInput
return [path, input, (opts as any)?.trpc] as const
}

export function createNuxtProxyDecoration<TRouter extends AnyRouter>(
name: string,
client: inferRouterProxyClient<TRouter>
) {
return createRecursiveProxy((opts) => {
const args = opts.args

const pathCopy = [name, ...opts.path]

// The last arg is for instance `.useMutation` or `.useQuery()`
const lastArg = pathCopy.pop()!

// The `path` ends up being something like `post.byId`
const path = pathCopy.join(".")

if (lastArg === "useMutation") {
const actualPath = Array.isArray(path) ? path[0] : path
return useMutation({
...args,
mutationKey: [actualPath.split(".")],
mutationFn: (input: any) => (client as any)[actualPath].mutate(input),
})
}

const [input, ...rest] = args

const queryKey = getQueryKey(path, input)

// Expose queryKey helper
if (lastArg === "getQueryKey") {
return getArrayQueryKey(queryKey, (rest[0] as any) ?? "any")
}

if (lastArg === "useQuery") {
const { trpc, ...options } = rest[0] || ({} as any)
return useQuery({
...options,
queryKey,
queryFn: () => (client as any)[path].query(input, trpc),
})
}

return (client as any)[path][lastArg](input)
})
}

export function createTRPCNuxtClient<TRouter extends AnyRouter>(
opts: CreateTRPCClientOptions<TRouter>
) {
const client = createTRPCProxyClient<TRouter>(opts)

const decoratedClient = createFlatProxy((key) => {
return createNuxtProxyDecoration(key, client)
}) as DecoratedProcedureRecord<TRouter["_def"]["record"], TRouter>

return decoratedClient
}

export { httpBatchLink, httpLink } from "../client-shared/links"
Loading