mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 12:14:40 +01:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
986b661e99 | ||
|
|
77325a6699 | ||
|
|
6dcb4ce8a6 |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "trpc-nuxt",
|
||||
"type": "module",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"packageManager": "pnpm@7.1.1",
|
||||
"license": "MIT",
|
||||
"main": "./dist/module.cjs",
|
||||
|
||||
19
playground/pages/cookie.vue
Normal file
19
playground/pages/cookie.vue
Normal file
@@ -0,0 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
const counter = useCookie('counter')
|
||||
counter.value = counter.value || Math.round(Math.random() * 1000)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1> Counter: {{ counter || '-' }}</h1>
|
||||
<button @click="counter = null">
|
||||
reset
|
||||
</button>
|
||||
<button @click="counter--">
|
||||
-
|
||||
</button>
|
||||
<button @click="counter++">
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,5 +1,8 @@
|
||||
import * as trpc from '@trpc/server'
|
||||
import type { inferAsyncReturnType } from '@trpc/server'
|
||||
import { z } from 'zod'
|
||||
import type { CompatibilityEvent } from 'h3'
|
||||
import { useCookies } from 'h3'
|
||||
|
||||
const baseURL = 'https://jsonplaceholder.typicode.com'
|
||||
|
||||
@@ -12,7 +15,7 @@ const TodoShape = z.object({
|
||||
|
||||
export type Todo = z.infer<typeof TodoShape>
|
||||
|
||||
export const router = trpc.router()
|
||||
export const router = trpc.router<Context>()
|
||||
.query('getTodos', {
|
||||
async resolve() {
|
||||
return await $fetch<Todo[]>(`${baseURL}/todos`)
|
||||
@@ -33,3 +36,18 @@ export const router = trpc.router()
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export async function createContext(event: CompatibilityEvent) {
|
||||
// Create your context based on the request object
|
||||
// Will be available as `ctx` in all your resolvers
|
||||
|
||||
// This is just an example of something you'd might want to do in your ctx fn
|
||||
// const x = useCookies(event)
|
||||
console.log('Headers', event.req.headers)
|
||||
|
||||
return {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
type Context = inferAsyncReturnType<typeof createContext>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { fileURLToPath } from 'url'
|
||||
import { join } from 'pathe'
|
||||
import { join, resolve } from 'pathe'
|
||||
import { defu } from 'defu'
|
||||
|
||||
import { addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
||||
import { addPluginTemplate, addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
||||
|
||||
export interface ModuleOptions {
|
||||
baseURL: string
|
||||
@@ -20,7 +20,7 @@ export default defineNuxtModule<ModuleOptions>({
|
||||
},
|
||||
async setup(options, nuxt) {
|
||||
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
||||
nuxt.options.build.transpile.push(runtimeDir, '#build/trpc-client', '#build/trpc-handler', '#build/trpc-helpers')
|
||||
nuxt.options.build.transpile.push(runtimeDir, '#build/trpc-client', '#build/trpc-handler')
|
||||
|
||||
const handlerPath = join(nuxt.options.buildDir, 'trpc-handler.ts')
|
||||
const trpcOptionsPath = join(nuxt.options.rootDir, 'server/trpc')
|
||||
@@ -48,18 +48,22 @@ export default defineNuxtModule<ModuleOptions>({
|
||||
write: true,
|
||||
getContents() {
|
||||
return `
|
||||
import * as trpc from '@trpc/client'
|
||||
import type { router } from '${trpcOptionsPath}'
|
||||
|
||||
const client = trpc.createTRPCClient<typeof router>({
|
||||
url: '${finalConfig.baseURL}${finalConfig.trpcURL}',
|
||||
})
|
||||
|
||||
export const useClient = () => client
|
||||
export const useClient = () => {
|
||||
const { $client } = useNuxtApp()
|
||||
return $client
|
||||
}
|
||||
`
|
||||
},
|
||||
})
|
||||
|
||||
addPluginTemplate({
|
||||
src: resolve(runtimeDir, 'plugin.ts'),
|
||||
write: true,
|
||||
options: {
|
||||
url: `${finalConfig.baseURL}${finalConfig.trpcURL}`,
|
||||
},
|
||||
})
|
||||
|
||||
addTemplate({
|
||||
filename: 'trpc-handler.ts',
|
||||
write: true,
|
||||
|
||||
@@ -9,7 +9,6 @@ import type { ProcedureRecord, inferHandlerInput, inferProcedureInput, inferProc
|
||||
import type { TRPCClientErrorLike } from '@trpc/client'
|
||||
import { objectHash } from 'ohash'
|
||||
import { useAsyncData, useState } from '#app'
|
||||
import { useClient } from '#build/trpc-client'
|
||||
// @ts-expect-error: Resolved by Nuxt
|
||||
import type { router } from '~/server/trpc'
|
||||
|
||||
@@ -38,12 +37,12 @@ export async function useAsyncQuery<
|
||||
pathAndInput: [path: TPath, ...args: inferHandlerInput<TQueries[TPath]>],
|
||||
options: AsyncDataOptions<TOutput, Transform, PickKeys> = {},
|
||||
): Promise<AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, TError>> {
|
||||
const client = useClient()
|
||||
const { $client } = useNuxtApp()
|
||||
const key = `${pathAndInput[0]}-${objectHash(pathAndInput[1] ? JSON.stringify(pathAndInput[1]) : '')}`
|
||||
const serverError = useState<TError | null>(`error-${key}`, () => null)
|
||||
const { error, data, ...rest } = await useAsyncData(
|
||||
key,
|
||||
() => client.query(...pathAndInput),
|
||||
() => $client.query(...pathAndInput),
|
||||
options,
|
||||
)
|
||||
|
||||
|
||||
18
src/runtime/plugin.ts
Normal file
18
src/runtime/plugin.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import * as trpc from '@trpc/client'
|
||||
import { defineNuxtPlugin, useRequestHeaders } from '#app'
|
||||
import type { router } from '~/server/trpc'
|
||||
|
||||
const options = JSON.parse('<%= JSON.stringify(options) %>')
|
||||
|
||||
export default defineNuxtPlugin(() => {
|
||||
const client = trpc.createTRPCClient<typeof router>({
|
||||
url: options.url as string,
|
||||
headers: useRequestHeaders(),
|
||||
})
|
||||
|
||||
return {
|
||||
provide: {
|
||||
client,
|
||||
},
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user