mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-20 15:01:44 +01:00
Compare commits
51 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0bb648bb08 | ||
|
|
ca2344ad86 | ||
|
|
004e655194 | ||
|
|
fca82a027e | ||
|
|
7995e892db | ||
|
|
8168a46985 | ||
|
|
2a23f4303d | ||
|
|
ff4bbebb0b | ||
|
|
354bf5d707 | ||
|
|
e7d160ee48 | ||
|
|
9bf6d57c2c | ||
|
|
6bca1e621d | ||
|
|
a8e5538b05 | ||
|
|
24ecb41429 | ||
|
|
e8bf427d2b | ||
|
|
347d49482f | ||
|
|
2f7a1276ad | ||
|
|
f6db0c78cd | ||
|
|
d3203f0536 | ||
|
|
83e2b2810d | ||
|
|
2b4fff9faa | ||
|
|
752fe721a2 | ||
|
|
808cac4756 | ||
|
|
0c44f73c9f | ||
|
|
182875a781 | ||
|
|
0298f836b8 | ||
|
|
ea50430945 | ||
|
|
0e240663ca | ||
|
|
bdeada0e6e | ||
|
|
fd9b86fb18 | ||
|
|
5fab0e54b0 | ||
|
|
7d2f464699 | ||
|
|
fdb9c2b474 | ||
|
|
4ed504e1e9 | ||
|
|
92747711c6 | ||
|
|
3646e8cdfe | ||
|
|
88214185a8 | ||
|
|
ad03ae7b65 | ||
|
|
09e8ab536a | ||
|
|
f7dadd482d | ||
|
|
7b69cff1ed | ||
|
|
f2d7763fa4 | ||
|
|
20f5a08cbd | ||
|
|
75980c0953 | ||
|
|
a6f61d404f | ||
|
|
e53d1be61e | ||
|
|
d152ebc7be | ||
|
|
f6daa2b7c3 | ||
|
|
7962c7f61e | ||
|
|
453845fb14 | ||
|
|
ee3ee485ba |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -49,3 +49,5 @@ coverage
|
|||||||
Network Trash Folder
|
Network Trash Folder
|
||||||
Temporary Items
|
Temporary Items
|
||||||
.apdisk
|
.apdisk
|
||||||
|
|
||||||
|
.vercel
|
||||||
|
|||||||
2
.nuxtrc
Normal file
2
.nuxtrc
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
imports.autoImport=false
|
||||||
|
typescript.includeWorkspace=true
|
||||||
15
README.md
15
README.md
@@ -15,12 +15,10 @@ End-to-end typesafe APIs with [tRPC.io](https://trpc.io/) in Nuxt applications.
|
|||||||
</figure>
|
</figure>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**⚠️ Currently works on Node v16 until [this issue](https://github.com/trpc/trpc/issues/2420) gets fixed.**
|
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm i trpc-nuxt
|
npm i trpc-nuxt@0.3
|
||||||
```
|
```
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
@@ -30,8 +28,9 @@ import { defineNuxtConfig } from 'nuxt'
|
|||||||
export default defineNuxtConfig({
|
export default defineNuxtConfig({
|
||||||
modules: ['trpc-nuxt'],
|
modules: ['trpc-nuxt'],
|
||||||
trpc: {
|
trpc: {
|
||||||
baseURL: 'http://localhost:3000', // defaults to http://localhost:3000
|
baseURL: '', // Set empty string (default) to make requests by relative address
|
||||||
endpoint: '/trpc', // defaults to /trpc
|
endpoint: '/trpc', // defaults to /trpc
|
||||||
|
installPlugin: true, // defaults to true. Add @trpc/client plugin and composables
|
||||||
},
|
},
|
||||||
typescript: {
|
typescript: {
|
||||||
strict: true // required to make input/output types work
|
strict: true // required to make input/output types work
|
||||||
@@ -115,6 +114,8 @@ headers.value.Authorization = `Bearer ${token}`
|
|||||||
// All client calls will now include the Authorization header.
|
// All client calls will now include the Authorization header.
|
||||||
```
|
```
|
||||||
|
|
||||||
|
If your app needs transformers and other option that needs to be passed in `@trpc/client`, you will need to opt-out of the plugin by setting `installPlugin` to false in your `nuxt.config.ts` file and create your own. You can just copy the contents of the client plugin [here](https://github.com/wobsoriano/trpc-nuxt/blob/master/src/runtime/client.ts).
|
||||||
|
|
||||||
## Options
|
## Options
|
||||||
|
|
||||||
trpc-nuxt accepts the following options exposed under `~/server/trpc/index.ts`:
|
trpc-nuxt accepts the following options exposed under `~/server/trpc/index.ts`:
|
||||||
@@ -122,14 +123,14 @@ trpc-nuxt accepts the following options exposed under `~/server/trpc/index.ts`:
|
|||||||
```ts
|
```ts
|
||||||
import * as trpc from '@trpc/server'
|
import * as trpc from '@trpc/server'
|
||||||
import type { inferAsyncReturnType } from '@trpc/server'
|
import type { inferAsyncReturnType } from '@trpc/server'
|
||||||
import type { CompatibilityEvent } from 'h3'
|
import type { H3Event } from 'h3'
|
||||||
import type { OnErrorPayload } from 'trpc-nuxt/api'
|
import type { OnErrorPayload } from 'trpc-nuxt/api'
|
||||||
|
|
||||||
export const router = trpc.router<inferAsyncReturnType<typeof createContext>>()
|
export const router = trpc.router<inferAsyncReturnType<typeof createContext>>()
|
||||||
|
|
||||||
// Optional
|
// Optional
|
||||||
// https://trpc.io/docs/context
|
// https://trpc.io/docs/context
|
||||||
export const createContext = (event: CompatibilityEvent) => {
|
export const createContext = (event: H3Event) => {
|
||||||
// ...
|
// ...
|
||||||
return {
|
return {
|
||||||
/** context data */
|
/** context data */
|
||||||
@@ -161,7 +162,7 @@ export const onError = (payload: OnErrorPayload<typeof router>) => {
|
|||||||
- [Error Formatting](/recipes/error-formatting.md)
|
- [Error Formatting](/recipes/error-formatting.md)
|
||||||
- [Inference Helpers](/recipes/inference-helpers.md)
|
- [Inference Helpers](/recipes/inference-helpers.md)
|
||||||
|
|
||||||
Learn more about tRPC.io [here](https://trpc.io/docs).
|
Learn more about tRPC.io [here](https://trpc.io/docs/v9).
|
||||||
|
|
||||||
## Recommended IDE Setup
|
## Recommended IDE Setup
|
||||||
|
|
||||||
|
|||||||
64
package.json
64
package.json
@@ -1,66 +1,66 @@
|
|||||||
{
|
{
|
||||||
"name": "trpc-nuxt",
|
"name": "trpc-nuxt",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"version": "0.2.8",
|
"version": "0.3.7",
|
||||||
"packageManager": "pnpm@7.5.0",
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"main": "./dist/module.cjs",
|
|
||||||
"types": "./dist/types.d.ts",
|
|
||||||
"exports": {
|
"exports": {
|
||||||
"./package.json": "./package.json",
|
"./package.json": "./package.json",
|
||||||
".": {
|
".": {
|
||||||
"import": "./dist/module.mjs",
|
"require": "./dist/module.cjs",
|
||||||
"require": "./dist/module.cjs"
|
"import": "./dist/module.mjs"
|
||||||
},
|
},
|
||||||
"./api": {
|
"./api": {
|
||||||
"import": "./dist/runtime/api.mjs",
|
"types": "./dist/runtime/api.d.ts",
|
||||||
"types": "./dist/runtime/api.d.ts"
|
"import": "./dist/runtime/api.mjs"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"main": "./dist/module.cjs",
|
||||||
|
"types": "./dist/types.d.ts",
|
||||||
"files": [
|
"files": [
|
||||||
"dist",
|
"dist",
|
||||||
"*.d.ts"
|
"*.d.ts"
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepublishOnly": "nr build",
|
|
||||||
"build": "nuxt-module-build",
|
"build": "nuxt-module-build",
|
||||||
"play": "nr build && nuxi dev playground",
|
"dev": "nuxi dev playground",
|
||||||
"build:playground": "nuxi build playground",
|
"dev:build": "nuxi build playground",
|
||||||
|
"dev:preview": "nuxi preview playground",
|
||||||
|
"dev:prepare": "nuxt-module-build --stub && nuxi prepare playground",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"lint:fix": "eslint . --fix",
|
"lint:fix": "eslint . --fix",
|
||||||
"release": "bumpp --commit --push --tag && npm publish",
|
"release": "bumpp --commit --push --tag && npm publish",
|
||||||
"prepare": "nuxi prepare playground"
|
"prepare": "nuxi prepare playground",
|
||||||
|
"prepublishOnly": "pnpm build"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@trpc/client": "<10.0.0",
|
||||||
|
"@trpc/server": "<10.0.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nuxt/kit": "3.0.0-rc.9",
|
"@nuxt/kit": "3.0.0",
|
||||||
"@trpc/client": "^9.27.2",
|
"@trpc/client": "^9.27.4",
|
||||||
"@trpc/server": "^9.27.2",
|
"@trpc/server": "^9.27.4",
|
||||||
"dedent": "^0.7.0",
|
"dedent": "^0.7.0",
|
||||||
"defu": "^6.0.0",
|
"defu": "^6.1.1",
|
||||||
"h3": "^0.7.10",
|
"h3": "^1.0.2",
|
||||||
"ohash": "^0.1.5",
|
"ofetch": "^1.0.0",
|
||||||
"pathe": "^0.3.0",
|
"ohash": "^1.0.0",
|
||||||
"ufo": "^0.8.5"
|
"pathe": "^1.0.0",
|
||||||
|
"ufo": "^1.0.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@antfu/eslint-config": "^0.23.1",
|
"@antfu/eslint-config": "^0.34.0",
|
||||||
"@antfu/ni": "^0.16.2",
|
"@nuxt/module-builder": "^0.2.1",
|
||||||
"@nuxt/module-builder": "^0.1.7",
|
|
||||||
"@types/dedent": "^0.7.0",
|
"@types/dedent": "^0.7.0",
|
||||||
"bumpp": "^7.2.0",
|
"bumpp": "^8.2.1",
|
||||||
"eslint": "^8.14.0",
|
"eslint": "^8.25.0",
|
||||||
"nuxt": "3.0.0-rc.9",
|
"nuxt": "3.0.0",
|
||||||
"pnpm": "^7.5.0",
|
"zod": "^3.20.2"
|
||||||
"trpc-nuxt": "workspace:*",
|
|
||||||
"zod": "^3.16.0"
|
|
||||||
},
|
},
|
||||||
"eslintConfig": {
|
"eslintConfig": {
|
||||||
"extends": "@antfu",
|
"extends": "@antfu",
|
||||||
"rules": {
|
"rules": {
|
||||||
"no-console": "warn"
|
"no-console": "warn"
|
||||||
}
|
}
|
||||||
},
|
|
||||||
"volta": {
|
|
||||||
"node": "16.14.2"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,9 @@
|
|||||||
import { defineNuxtConfig } from 'nuxt'
|
|
||||||
import Module from '../src/module'
|
import Module from '../src/module'
|
||||||
|
|
||||||
// https://v3.nuxtjs.org/api/configuration/nuxt.config
|
// https://v3.nuxtjs.org/api/configuration/nuxt.config
|
||||||
export default defineNuxtConfig({
|
export default defineNuxtConfig({
|
||||||
modules: [Module],
|
modules: [Module],
|
||||||
runtimeConfig: {
|
runtimeConfig: {
|
||||||
baseURL: 'http://localhost:3000',
|
baseURL: '',
|
||||||
},
|
|
||||||
typescript: {
|
|
||||||
strict: true,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
<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,4 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { useAsyncQuery, useClient, useClientHeaders } from '#imports'
|
||||||
const client = useClient()
|
const client = useClient()
|
||||||
const headers = useClientHeaders()
|
const headers = useClientHeaders()
|
||||||
const { data: todos, pending, error, refresh } = await useAsyncQuery(['getTodos'])
|
const { data: todos, pending, error, refresh } = await useAsyncQuery(['getTodos'])
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { useAsyncQuery, useRoute } from '#imports'
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const { data: todo, pending, error } = await useAsyncQuery(['getTodo', Number(route.params.id)])
|
const { data: todo, pending, error } = await useAsyncQuery(['getTodo', Number(route.params.id)])
|
||||||
</script>
|
</script>
|
||||||
@@ -11,8 +12,8 @@ const { data: todo, pending, error } = await useAsyncQuery(['getTodo', Number(ro
|
|||||||
{{ error.data.code }}
|
{{ error.data.code }}
|
||||||
</div>
|
</div>
|
||||||
<div v-else>
|
<div v-else>
|
||||||
ID: {{ todo.id }} <br>
|
ID: {{ todo?.id }} <br>
|
||||||
Title: {{ todo.title }} <br>
|
Title: {{ todo?.title }} <br>
|
||||||
Completed: {{ todo.completed }}
|
Completed: {{ todo?.completed }}
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import * as trpc from '@trpc/server'
|
import * as trpc from '@trpc/server'
|
||||||
import type { inferAsyncReturnType } from '@trpc/server'
|
import type { inferAsyncReturnType } from '@trpc/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import type { CompatibilityEvent } from 'h3'
|
import type { H3Event } from 'h3'
|
||||||
|
|
||||||
const baseURL = 'https://jsonplaceholder.typicode.com'
|
const baseURL = 'https://jsonplaceholder.typicode.com'
|
||||||
|
|
||||||
@@ -29,7 +29,6 @@ export const router = trpc.router<Context>()
|
|||||||
.mutation('addTodo', {
|
.mutation('addTodo', {
|
||||||
input: TodoShape,
|
input: TodoShape,
|
||||||
async resolve(req) {
|
async resolve(req) {
|
||||||
console.log(req.input)
|
|
||||||
return await $fetch<Todo>(`${baseURL}/todos`, {
|
return await $fetch<Todo>(`${baseURL}/todos`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: req.input,
|
body: req.input,
|
||||||
@@ -37,13 +36,13 @@ export const router = trpc.router<Context>()
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
export async function createContext(event: CompatibilityEvent) {
|
export async function createContext(event: H3Event) {
|
||||||
// Create your context based on the request object
|
// Create your context based on the request object
|
||||||
// Will be available as `ctx` in all your resolvers
|
// 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
|
// This is just an example of something you'd might want to do in your ctx fn
|
||||||
// const x = useCookies(event)
|
// const x = useCookies(event)
|
||||||
console.log(event.req.headers)
|
console.log(event.node.req.headers)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
||||||
|
|||||||
3871
pnpm-lock.yaml
generated
3871
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -7,11 +7,11 @@ The `createContext`-function is called for each incoming request so here you can
|
|||||||
```ts
|
```ts
|
||||||
// ~/server/trpc/index.ts
|
// ~/server/trpc/index.ts
|
||||||
import type { inferAsyncReturnType } from '@trpc/server'
|
import type { inferAsyncReturnType } from '@trpc/server'
|
||||||
import type { CompatibilityEvent } from 'h3'
|
import type { H3Event } from 'h3'
|
||||||
import { decodeAndVerifyJwtToken } from '~/somewhere/in/your/app/utils'
|
import { decodeAndVerifyJwtToken } from '~/somewhere/in/your/app/utils'
|
||||||
|
|
||||||
// The app's context - is generated for each incoming request
|
// The app's context - is generated for each incoming request
|
||||||
export async function createContext({ req }: CompatibilityEvent) {
|
export async function createContext({ req }: H3Event) {
|
||||||
// Create your context based on the request object
|
// Create your context based on the request object
|
||||||
// Will be available as `ctx` in all your resolvers
|
// Will be available as `ctx` in all your resolvers
|
||||||
|
|
||||||
|
|||||||
@@ -3,56 +3,54 @@ import { join, resolve } from 'pathe'
|
|||||||
import { defu } from 'defu'
|
import { defu } from 'defu'
|
||||||
import dedent from 'dedent'
|
import dedent from 'dedent'
|
||||||
|
|
||||||
import { addImports, addPlugin, addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
import { addImports, addPlugin, addServerHandler, addTemplate, defineNuxtModule, useLogger } from '@nuxt/kit'
|
||||||
|
|
||||||
export interface ModuleOptions {
|
export interface ModuleOptions {
|
||||||
baseURL: string
|
baseURL: string
|
||||||
endpoint: string
|
endpoint: string
|
||||||
|
installPlugin?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const metaName = 'trpc-nuxt'
|
||||||
|
|
||||||
export default defineNuxtModule<ModuleOptions>({
|
export default defineNuxtModule<ModuleOptions>({
|
||||||
meta: {
|
meta: {
|
||||||
name: 'trpc-nuxt',
|
name: metaName,
|
||||||
configKey: 'trpc',
|
configKey: 'trpc',
|
||||||
},
|
},
|
||||||
defaults: {
|
defaults: {
|
||||||
baseURL: 'http://localhost:3000',
|
baseURL: '',
|
||||||
endpoint: '/trpc',
|
endpoint: '/trpc',
|
||||||
|
installPlugin: true,
|
||||||
},
|
},
|
||||||
async setup(options, nuxt) {
|
async setup(options, nuxt) {
|
||||||
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
const logger = useLogger(metaName)
|
||||||
nuxt.options.build.transpile.push(runtimeDir, '#build/trpc-handler')
|
|
||||||
|
|
||||||
const handlerPath = join(nuxt.options.buildDir, 'trpc-handler.ts')
|
const handlerPath = join(nuxt.options.buildDir, 'trpc-handler.ts')
|
||||||
const trpcOptionsPath = join(nuxt.options.srcDir, 'server/trpc')
|
const trpcOptionsPath = join(nuxt.options.srcDir, 'server/trpc')
|
||||||
|
|
||||||
|
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
||||||
|
nuxt.options.build.transpile.push(runtimeDir, handlerPath)
|
||||||
|
|
||||||
// Final resolved configuration
|
// Final resolved configuration
|
||||||
const finalConfig = nuxt.options.runtimeConfig.public.trpc = defu(nuxt.options.runtimeConfig.public.trpc, {
|
const finalConfig = nuxt.options.runtimeConfig.public.trpc = defu(nuxt.options.runtimeConfig.public.trpc, {
|
||||||
baseURL: options.baseURL,
|
baseURL: options.baseURL,
|
||||||
endpoint: options.endpoint,
|
endpoint: options.endpoint,
|
||||||
|
installPlugin: options.installPlugin,
|
||||||
})
|
})
|
||||||
|
|
||||||
addImports([
|
|
||||||
{ name: 'useClient', from: join(runtimeDir, 'client') },
|
|
||||||
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
|
||||||
{ name: 'useClientHeaders', from: join(runtimeDir, 'client') },
|
|
||||||
{ name: 'getQueryKey', from: join(runtimeDir, 'client') },
|
|
||||||
])
|
|
||||||
|
|
||||||
addServerHandler({
|
addServerHandler({
|
||||||
route: `${finalConfig.endpoint}/*`,
|
route: `${finalConfig.endpoint}/*`,
|
||||||
handler: handlerPath,
|
handler: handlerPath,
|
||||||
})
|
})
|
||||||
|
|
||||||
addPlugin(resolve(runtimeDir, 'plugin'))
|
|
||||||
|
|
||||||
addTemplate({
|
addTemplate({
|
||||||
filename: 'trpc-handler.ts',
|
filename: 'trpc-handler.ts',
|
||||||
write: true,
|
write: true,
|
||||||
getContents() {
|
getContents() {
|
||||||
return dedent`
|
return dedent`
|
||||||
import { createTRPCHandler } from 'trpc-nuxt/api'
|
import { createTRPCHandler } from ${JSON.stringify(join(runtimeDir, 'api'))};
|
||||||
import * as functions from '${trpcOptionsPath}'
|
import * as functions from ${JSON.stringify(trpcOptionsPath)};
|
||||||
|
|
||||||
export default createTRPCHandler({
|
export default createTRPCHandler({
|
||||||
...functions,
|
...functions,
|
||||||
@@ -61,6 +59,21 @@ export default defineNuxtModule<ModuleOptions>({
|
|||||||
`
|
`
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if (finalConfig.installPlugin) {
|
||||||
|
addImports([
|
||||||
|
{ name: 'useClient', from: join(runtimeDir, 'client') },
|
||||||
|
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
||||||
|
{ name: 'useClientHeaders', from: join(runtimeDir, 'client') },
|
||||||
|
{ name: 'getQueryKey', from: join(runtimeDir, 'client') },
|
||||||
|
])
|
||||||
|
|
||||||
|
addPlugin(resolve(runtimeDir, 'plugin'))
|
||||||
|
|
||||||
|
logger.success('Plugin successfully installed.')
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
logger.info('Plugin not installed. Create your own @trpc/client client plugin and composables.')
|
||||||
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -8,13 +8,13 @@ import type {
|
|||||||
inferRouterError,
|
inferRouterError,
|
||||||
} from '@trpc/server'
|
} from '@trpc/server'
|
||||||
import { createURL } from 'ufo'
|
import { createURL } from 'ufo'
|
||||||
import type { CompatibilityEvent } from 'h3'
|
import type { H3Event } from 'h3'
|
||||||
import { defineEventHandler, isMethod, useBody } from 'h3'
|
import { defineEventHandler, isMethod, readBody } from 'h3'
|
||||||
import type { TRPCResponse } from '@trpc/server/dist/declarations/src/rpc'
|
import type { TRPCResponse } from '@trpc/server/dist/declarations/src/rpc'
|
||||||
|
|
||||||
type MaybePromise<T> = T | Promise<T>
|
type MaybePromise<T> = T | Promise<T>
|
||||||
|
|
||||||
export type CreateContextFn<TRouter extends AnyRouter> = (event: CompatibilityEvent) => MaybePromise<inferRouterContext<TRouter>>
|
export type CreateContextFn<TRouter extends AnyRouter> = (event: H3Event) => MaybePromise<inferRouterContext<TRouter>>
|
||||||
|
|
||||||
export interface ResponseMetaFnPayload<TRouter extends AnyRouter> {
|
export interface ResponseMetaFnPayload<TRouter extends AnyRouter> {
|
||||||
data: TRPCResponse<unknown, inferRouterError<TRouter>>[]
|
data: TRPCResponse<unknown, inferRouterError<TRouter>>[]
|
||||||
@@ -30,7 +30,7 @@ export interface OnErrorPayload<TRouter extends AnyRouter> {
|
|||||||
error: TRPCError
|
error: TRPCError
|
||||||
type: ProcedureType | 'unknown'
|
type: ProcedureType | 'unknown'
|
||||||
path: string | undefined
|
path: string | undefined
|
||||||
req: CompatibilityEvent['req']
|
req: H3Event['node']['req']
|
||||||
input: unknown
|
input: unknown
|
||||||
ctx: undefined | inferRouterContext<TRouter>
|
ctx: undefined | inferRouterContext<TRouter>
|
||||||
}
|
}
|
||||||
@@ -54,7 +54,7 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
|||||||
const {
|
const {
|
||||||
req,
|
req,
|
||||||
res,
|
res,
|
||||||
} = event
|
} = event.node
|
||||||
|
|
||||||
const $url = createURL(req.url!)
|
const $url = createURL(req.url!)
|
||||||
|
|
||||||
@@ -63,7 +63,7 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
|||||||
req: {
|
req: {
|
||||||
method: req.method!,
|
method: req.method!,
|
||||||
headers: req.headers,
|
headers: req.headers,
|
||||||
body: isMethod(event, 'GET') ? null : await useBody(event),
|
body: isMethod(event, 'GET') ? null : await readBody(event),
|
||||||
query: $url.searchParams,
|
query: $url.searchParams,
|
||||||
},
|
},
|
||||||
path: $url.pathname.substring(endpoint.length + 1),
|
path: $url.pathname.substring(endpoint.length + 1),
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import type { ProcedureRecord, inferHandlerInput, inferProcedureInput, inferProc
|
|||||||
import type { TRPCClient, TRPCClientErrorLike } from '@trpc/client'
|
import type { TRPCClient, TRPCClientErrorLike } from '@trpc/client'
|
||||||
import { objectHash } from 'ohash'
|
import { objectHash } from 'ohash'
|
||||||
import type { Ref } from 'vue'
|
import type { Ref } from 'vue'
|
||||||
import { useAsyncData, useNuxtApp, useState } from '#app'
|
import { useAsyncData, useNuxtApp, useState } from '#imports'
|
||||||
import type { router } from '~/server/trpc'
|
import type { router } from '~/server/trpc'
|
||||||
|
|
||||||
type MaybeRef<T> = T | Ref<T>
|
type MaybeRef<T> = T | Ref<T>
|
||||||
@@ -51,25 +51,14 @@ export async function useAsyncQuery<
|
|||||||
): Promise<AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, TError>> {
|
): Promise<AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, TError>> {
|
||||||
const { $client } = useNuxtApp()
|
const { $client } = useNuxtApp()
|
||||||
const key = getQueryKey(pathAndInput)
|
const key = getQueryKey(pathAndInput)
|
||||||
const serverError = useState<TError | null>(`error-${key}`, () => null)
|
const result = await useAsyncData(
|
||||||
const { error, data, ...rest } = await useAsyncData(
|
|
||||||
key,
|
key,
|
||||||
() => $client.query(...pathAndInput),
|
() => $client.query(...pathAndInput),
|
||||||
// @ts-expect-error: Internal
|
// @ts-expect-error: Internal
|
||||||
options,
|
options,
|
||||||
)
|
)
|
||||||
|
|
||||||
if (process.server && error.value && !serverError.value)
|
return result as any
|
||||||
serverError.value = error.value as any
|
|
||||||
|
|
||||||
if (data.value)
|
|
||||||
serverError.value = null
|
|
||||||
|
|
||||||
return {
|
|
||||||
...rest,
|
|
||||||
data,
|
|
||||||
error: serverError,
|
|
||||||
} as any
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useClient(): TRPCClient<AppRouter> {
|
export function useClient(): TRPCClient<AppRouter> {
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import * as trpc from '@trpc/client'
|
import * as trpc from '@trpc/client'
|
||||||
import { unref } from 'vue'
|
import { unref } from 'vue'
|
||||||
|
import { FetchError } from 'ofetch'
|
||||||
import { useClientHeaders } from './client'
|
import { useClientHeaders } from './client'
|
||||||
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#app'
|
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#imports'
|
||||||
import type { router } from '~/server/trpc'
|
import type { router } from '~/server/trpc'
|
||||||
|
|
||||||
declare type AppRouter = typeof router
|
declare type AppRouter = typeof router
|
||||||
@@ -10,14 +11,28 @@ export default defineNuxtPlugin((nuxtApp) => {
|
|||||||
const config = useRuntimeConfig().public.trpc
|
const config = useRuntimeConfig().public.trpc
|
||||||
const headers = useRequestHeaders()
|
const headers = useRequestHeaders()
|
||||||
const otherHeaders = useClientHeaders()
|
const otherHeaders = useClientHeaders()
|
||||||
|
|
||||||
|
const baseURL = process.server ? '' : config.baseURL
|
||||||
const client = trpc.createTRPCClient<AppRouter>({
|
const client = trpc.createTRPCClient<AppRouter>({
|
||||||
url: `${config.baseURL}${config.endpoint}`,
|
url: `${baseURL}${config.endpoint}`,
|
||||||
headers: () => {
|
headers: () => {
|
||||||
return {
|
return {
|
||||||
...unref(otherHeaders),
|
...unref(otherHeaders),
|
||||||
...headers,
|
...headers,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
fetch: (input, options) =>
|
||||||
|
globalThis.$fetch.raw(input.toString(), options)
|
||||||
|
.catch((e) => {
|
||||||
|
if (e instanceof FetchError && e.response)
|
||||||
|
return e.response
|
||||||
|
|
||||||
|
throw e
|
||||||
|
})
|
||||||
|
.then(response => ({
|
||||||
|
...response,
|
||||||
|
json: () => Promise.resolve(response._data),
|
||||||
|
})),
|
||||||
})
|
})
|
||||||
|
|
||||||
nuxtApp.provide('client', client)
|
nuxtApp.provide('client', client)
|
||||||
|
|||||||
Reference in New Issue
Block a user