mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 20:19:33 +01:00
Compare commits
134 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 | ||
|
|
cdf29bee67 | ||
|
|
d3d35404b1 | ||
|
|
e57c919157 | ||
|
|
d0fffbbc64 | ||
|
|
433d5ada46 | ||
|
|
5d180460af | ||
|
|
8991148d39 | ||
|
|
dd05285d65 | ||
|
|
d058ff241a | ||
|
|
fb4894e264 | ||
|
|
186faff140 | ||
|
|
b9cdb228b7 | ||
|
|
1e67434a8f | ||
|
|
019bb20e50 | ||
|
|
695ce4c56e | ||
|
|
38649b7023 | ||
|
|
5cfef32baa | ||
|
|
8497289c65 | ||
|
|
224c4b317b | ||
|
|
d5d6780ca8 | ||
|
|
252d0f6692 | ||
|
|
d022710591 | ||
|
|
a926968f13 | ||
|
|
a8eba5ab8d | ||
|
|
5871528d67 | ||
|
|
def9d0b19d | ||
|
|
34f50fc4d6 | ||
|
|
9fe1469eba | ||
|
|
e48d7cd42c | ||
|
|
2b517ad77b | ||
|
|
77ee994e13 | ||
|
|
67a8a2a3ed | ||
|
|
556b5c8e08 | ||
|
|
85154f12d7 | ||
|
|
26ce46e12b | ||
|
|
c2cfd9a214 | ||
|
|
f736545128 | ||
|
|
59a9eb5f95 | ||
|
|
48fc19076f | ||
|
|
6b83e5d4ea | ||
|
|
0358a258d7 | ||
|
|
8e7f33c9d2 | ||
|
|
b8f4af2df3 | ||
|
|
666751678c | ||
|
|
cab89aaa66 | ||
|
|
4c9850fafc | ||
|
|
07693009f8 | ||
|
|
dceade155c | ||
|
|
4012249f09 | ||
|
|
38eda2c4d6 | ||
|
|
9468af75f4 | ||
|
|
ea24a67a6d | ||
|
|
5e8d04741c | ||
|
|
1032e65a0d | ||
|
|
f261d3feeb | ||
|
|
b1ca09e986 | ||
|
|
b804429fc0 | ||
|
|
7df64296ff | ||
|
|
a53d823f5e | ||
|
|
feef3dde6b | ||
|
|
82ee2ce672 | ||
|
|
f62a13766a | ||
|
|
c7888e81ed | ||
|
|
c77eb68f5d | ||
|
|
333539569c | ||
|
|
e5c40f183b | ||
|
|
977a9e1465 | ||
|
|
2620379e02 | ||
|
|
e4f42d5322 | ||
|
|
ad28a9124e | ||
|
|
273bda980b | ||
|
|
9c8509f79c | ||
|
|
2ce29137ce | ||
|
|
e9c5307e23 | ||
|
|
bbdabf544c | ||
|
|
aed10ac5b8 | ||
|
|
4b2c714658 | ||
|
|
43e9fefdbd | ||
|
|
dabda23976 | ||
|
|
af89f32275 | ||
|
|
1f27b871fb | ||
|
|
281e4c05a0 | ||
|
|
38ac520b97 |
22
.github/workflows/release.yml
vendored
Normal file
22
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16.x
|
||||
|
||||
- run: npx changelogithub
|
||||
env:
|
||||
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -49,3 +49,5 @@ coverage
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
.vercel
|
||||
|
||||
2
.nuxtrc
Normal file
2
.nuxtrc
Normal file
@@ -0,0 +1,2 @@
|
||||
imports.autoImport=false
|
||||
typescript.includeWorkspace=true
|
||||
20
README.md
20
README.md
@@ -18,7 +18,7 @@ End-to-end typesafe APIs with [tRPC.io](https://trpc.io/) in Nuxt applications.
|
||||
## Install
|
||||
|
||||
```bash
|
||||
npm i trpc-nuxt
|
||||
npm i trpc-nuxt@0.3
|
||||
```
|
||||
|
||||
```ts
|
||||
@@ -28,11 +28,12 @@ import { defineNuxtConfig } from 'nuxt'
|
||||
export default defineNuxtConfig({
|
||||
modules: ['trpc-nuxt'],
|
||||
trpc: {
|
||||
baseURL: 'http://localhost:3000', // defaults to http://localhost:3000
|
||||
trpcURL: '/api/trpc', // defaults to /api/trpc
|
||||
baseURL: '', // Set empty string (default) to make requests by relative address
|
||||
endpoint: '/trpc', // defaults to /trpc
|
||||
installPlugin: true, // defaults to true. Add @trpc/client plugin and composables
|
||||
},
|
||||
typescript: {
|
||||
strict: true // set this to true to make input/output types work
|
||||
strict: true // required to make input/output types work
|
||||
}
|
||||
})
|
||||
```
|
||||
@@ -101,7 +102,7 @@ const {
|
||||
|
||||
## useClientHeaders
|
||||
|
||||
A composable that lets you add additional properties to pass to the tRPC Client. It uses `useStorage` from [@vueuse/core](https://vueuse.org/core/usestorage).
|
||||
A composable that lets you add additional properties to pass to the tRPC Client. It uses `useState` from [nuxt 3](https://v3.nuxtjs.org/api/composables/use-state).
|
||||
|
||||
```ts
|
||||
const headers = useClientHeaders()
|
||||
@@ -111,9 +112,10 @@ const { data: token } = await useAsyncQuery(['auth.login', { username, password
|
||||
headers.value.Authorization = `Bearer ${token}`
|
||||
|
||||
// All client calls will now include the Authorization header.
|
||||
// For SSR, please follow this until I found a solution https://github.com/trpc/trpc/discussions/1686
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
trpc-nuxt accepts the following options exposed under `~/server/trpc/index.ts`:
|
||||
@@ -121,14 +123,14 @@ trpc-nuxt accepts the following options exposed under `~/server/trpc/index.ts`:
|
||||
```ts
|
||||
import * as trpc 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'
|
||||
|
||||
export const router = trpc.router<inferAsyncReturnType<typeof createContext>>()
|
||||
|
||||
// Optional
|
||||
// https://trpc.io/docs/context
|
||||
export const createContext = (event: CompatibilityEvent) => {
|
||||
export const createContext = (event: H3Event) => {
|
||||
// ...
|
||||
return {
|
||||
/** context data */
|
||||
@@ -160,7 +162,7 @@ export const onError = (payload: OnErrorPayload<typeof router>) => {
|
||||
- [Error Formatting](/recipes/error-formatting.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
|
||||
|
||||
|
||||
73
package.json
73
package.json
@@ -1,61 +1,66 @@
|
||||
{
|
||||
"name": "trpc-nuxt",
|
||||
"type": "module",
|
||||
"version": "0.1.17",
|
||||
"packageManager": "pnpm@7.1.1",
|
||||
"version": "0.3.7",
|
||||
"license": "MIT",
|
||||
"main": "./dist/module.cjs",
|
||||
"types": "./dist/types.d.ts",
|
||||
"exports": {
|
||||
"./package.json": "./package.json",
|
||||
".": {
|
||||
"import": "./dist/module.mjs",
|
||||
"require": "./dist/module.cjs"
|
||||
"require": "./dist/module.cjs",
|
||||
"import": "./dist/module.mjs"
|
||||
},
|
||||
"./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": [
|
||||
"dist",
|
||||
"*.d.ts"
|
||||
],
|
||||
"scripts": {
|
||||
"prepublishOnly": "nr build",
|
||||
"build": "nuxt-module-build",
|
||||
"play": "nr build && nuxi dev playground",
|
||||
"build:playground": "nuxi build playground",
|
||||
"dev": "nuxi dev playground",
|
||||
"dev:build": "nuxi build playground",
|
||||
"dev:preview": "nuxi preview playground",
|
||||
"dev:prepare": "nuxt-module-build --stub && nuxi prepare playground",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"release": "bumpp --commit --push --tag && pnpm publish",
|
||||
"prepare": "nuxi prepare playground"
|
||||
"release": "bumpp --commit --push --tag && npm publish",
|
||||
"prepare": "nuxi prepare playground",
|
||||
"prepublishOnly": "pnpm build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@trpc/client": "<10.0.0",
|
||||
"@trpc/server": "<10.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nuxt/kit": "^3.0.0-rc.3",
|
||||
"@trpc/client": "^9.23.3",
|
||||
"@trpc/server": "^9.23.2",
|
||||
"@vueuse/core": "^8.5.0",
|
||||
"@vueuse/nuxt": "^8.5.0",
|
||||
"defu": "^6.0.0",
|
||||
"h3": "^0.7.8",
|
||||
"pathe": "^0.3.0",
|
||||
"ufo": "^0.8.4"
|
||||
"@nuxt/kit": "3.0.0",
|
||||
"@trpc/client": "^9.27.4",
|
||||
"@trpc/server": "^9.27.4",
|
||||
"dedent": "^0.7.0",
|
||||
"defu": "^6.1.1",
|
||||
"h3": "^1.0.2",
|
||||
"ofetch": "^1.0.0",
|
||||
"ohash": "^1.0.0",
|
||||
"pathe": "^1.0.0",
|
||||
"ufo": "^1.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^0.23.1",
|
||||
"@antfu/ni": "^0.16.2",
|
||||
"@nuxt/module-builder": "latest",
|
||||
"bumpp": "^7.1.1",
|
||||
"eslint": "^8.14.0",
|
||||
"nuxt": "^3.0.0-rc.3",
|
||||
"ohash": "^0.1.0",
|
||||
"pnpm": "^7.1.1",
|
||||
"superjson": "^1.9.1",
|
||||
"trpc-nuxt": "workspace:*",
|
||||
"zod": "^3.16.0"
|
||||
"@antfu/eslint-config": "^0.34.0",
|
||||
"@nuxt/module-builder": "^0.2.1",
|
||||
"@types/dedent": "^0.7.0",
|
||||
"bumpp": "^8.2.1",
|
||||
"eslint": "^8.25.0",
|
||||
"nuxt": "3.0.0",
|
||||
"zod": "^3.20.2"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": "@antfu"
|
||||
"extends": "@antfu",
|
||||
"rules": {
|
||||
"no-console": "warn"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import { defineNuxtConfig } from 'nuxt'
|
||||
import Module from '../src/module'
|
||||
|
||||
// https://v3.nuxtjs.org/api/configuration/nuxt.config
|
||||
export default defineNuxtConfig({
|
||||
modules: [Module],
|
||||
runtimeConfig: {
|
||||
baseURL: 'http://localhost:3000',
|
||||
},
|
||||
typescript: {
|
||||
strict: true,
|
||||
baseURL: '',
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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,12 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import { useAsyncQuery, useClient, useClientHeaders } from '#imports'
|
||||
const client = useClient()
|
||||
const headers = useClientHeader({ authorization: 'asdada' })
|
||||
const headers = useClientHeaders()
|
||||
const { data: todos, pending, error, refresh } = await useAsyncQuery(['getTodos'])
|
||||
|
||||
console.log(headers.value)
|
||||
|
||||
const addHeader = () => {
|
||||
// headers.value.cookie = 'counter=69'
|
||||
headers.value.authorization = 'Bearer abcdefghijklmnop'
|
||||
console.log(headers.value)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { useAsyncQuery, useRoute } from '#imports'
|
||||
const route = useRoute()
|
||||
const { data: todo, pending, error } = await useAsyncQuery(['getTodo', Number(route.params.id)])
|
||||
</script>
|
||||
@@ -11,8 +12,8 @@ const { data: todo, pending, error } = await useAsyncQuery(['getTodo', Number(ro
|
||||
{{ error.data.code }}
|
||||
</div>
|
||||
<div v-else>
|
||||
ID: {{ todo.id }} <br>
|
||||
Title: {{ todo.title }} <br>
|
||||
Completed: {{ todo.completed }}
|
||||
ID: {{ todo?.id }} <br>
|
||||
Title: {{ todo?.title }} <br>
|
||||
Completed: {{ todo?.completed }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
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'
|
||||
import type { H3Event } from 'h3'
|
||||
|
||||
const baseURL = 'https://jsonplaceholder.typicode.com'
|
||||
|
||||
@@ -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
|
||||
// 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(event.req.headers)
|
||||
console.log(event.node.req.headers)
|
||||
|
||||
return {
|
||||
|
||||
|
||||
4641
pnpm-lock.yaml
generated
4641
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,2 +1,2 @@
|
||||
packages:
|
||||
- playground/*
|
||||
- playground
|
||||
|
||||
@@ -7,11 +7,11 @@ The `createContext`-function is called for each incoming request so here you can
|
||||
```ts
|
||||
// ~/server/trpc/index.ts
|
||||
import type { inferAsyncReturnType } from '@trpc/server'
|
||||
import type { CompatibilityEvent } from 'h3'
|
||||
import type { H3Event } from 'h3'
|
||||
import { decodeAndVerifyJwtToken } from '~/somewhere/in/your/app/utils'
|
||||
|
||||
// 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
|
||||
// Will be available as `ctx` in all your resolvers
|
||||
|
||||
|
||||
@@ -1,69 +1,79 @@
|
||||
import { fileURLToPath } from 'url'
|
||||
import { join, resolve } from 'pathe'
|
||||
import { defu } from 'defu'
|
||||
import dedent from 'dedent'
|
||||
|
||||
import { addPlugin, addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
||||
import { addImports, addPlugin, addServerHandler, addTemplate, defineNuxtModule, useLogger } from '@nuxt/kit'
|
||||
|
||||
export interface ModuleOptions {
|
||||
baseURL: string
|
||||
trpcURL: string
|
||||
endpoint: string
|
||||
installPlugin?: boolean
|
||||
}
|
||||
|
||||
const metaName = 'trpc-nuxt'
|
||||
|
||||
export default defineNuxtModule<ModuleOptions>({
|
||||
meta: {
|
||||
name: 'trpc-nuxt',
|
||||
name: metaName,
|
||||
configKey: 'trpc',
|
||||
},
|
||||
defaults: {
|
||||
baseURL: 'http://localhost:3000',
|
||||
trpcURL: '/api/trpc',
|
||||
baseURL: '',
|
||||
endpoint: '/trpc',
|
||||
installPlugin: true,
|
||||
},
|
||||
async setup(options, nuxt) {
|
||||
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
||||
nuxt.options.build.transpile.push(runtimeDir, '#build/trpc-handler')
|
||||
const logger = useLogger(metaName)
|
||||
|
||||
const handlerPath = join(nuxt.options.buildDir, 'trpc-handler.ts')
|
||||
const trpcOptionsPath = join(nuxt.options.rootDir, 'server/trpc')
|
||||
const trpcOptionsPath = join(nuxt.options.srcDir, 'server/trpc')
|
||||
|
||||
// Add vueuse
|
||||
nuxt.options.modules.push('@vueuse/nuxt')
|
||||
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
||||
nuxt.options.build.transpile.push(runtimeDir, handlerPath)
|
||||
|
||||
// Final resolved configuration
|
||||
const finalConfig = nuxt.options.runtimeConfig.public.trpc = defu(nuxt.options.runtimeConfig.public.trpc, {
|
||||
baseURL: options.baseURL,
|
||||
trpcURL: options.trpcURL,
|
||||
})
|
||||
|
||||
nuxt.hook('autoImports:extend', (imports) => {
|
||||
imports.push(
|
||||
{ name: 'useClient', from: join(runtimeDir, 'client') },
|
||||
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
||||
{ name: 'useClientHeader', from: join(runtimeDir, 'client') },
|
||||
)
|
||||
endpoint: options.endpoint,
|
||||
installPlugin: options.installPlugin,
|
||||
})
|
||||
|
||||
addServerHandler({
|
||||
route: `${finalConfig.trpcURL}/*`,
|
||||
route: `${finalConfig.endpoint}/*`,
|
||||
handler: handlerPath,
|
||||
})
|
||||
|
||||
addPlugin(resolve(runtimeDir, 'plugin'))
|
||||
|
||||
addTemplate({
|
||||
filename: 'trpc-handler.ts',
|
||||
write: true,
|
||||
getContents() {
|
||||
return `
|
||||
import { createTRPCHandler } from 'trpc-nuxt/api'
|
||||
import * as functions from '${trpcOptionsPath}'
|
||||
return dedent`
|
||||
import { createTRPCHandler } from ${JSON.stringify(join(runtimeDir, 'api'))};
|
||||
import * as functions from ${JSON.stringify(trpcOptionsPath)};
|
||||
|
||||
export default createTRPCHandler({
|
||||
...functions,
|
||||
trpcURL: '${finalConfig.trpcURL}'
|
||||
endpoint: '${finalConfig.endpoint}'
|
||||
})
|
||||
`
|
||||
},
|
||||
})
|
||||
|
||||
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,
|
||||
} from '@trpc/server'
|
||||
import { createURL } from 'ufo'
|
||||
import type { CompatibilityEvent } from 'h3'
|
||||
import { defineEventHandler, isMethod, useBody } from 'h3'
|
||||
import type { H3Event } from 'h3'
|
||||
import { defineEventHandler, isMethod, readBody } from 'h3'
|
||||
import type { TRPCResponse } from '@trpc/server/dist/declarations/src/rpc'
|
||||
|
||||
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> {
|
||||
data: TRPCResponse<unknown, inferRouterError<TRouter>>[]
|
||||
@@ -30,7 +30,7 @@ export interface OnErrorPayload<TRouter extends AnyRouter> {
|
||||
error: TRPCError
|
||||
type: ProcedureType | 'unknown'
|
||||
path: string | undefined
|
||||
req: CompatibilityEvent['req']
|
||||
req: H3Event['node']['req']
|
||||
input: unknown
|
||||
ctx: undefined | inferRouterContext<TRouter>
|
||||
}
|
||||
@@ -42,31 +42,31 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
||||
createContext,
|
||||
responseMeta,
|
||||
onError,
|
||||
trpcURL,
|
||||
endpoint,
|
||||
}: {
|
||||
router: Router
|
||||
createContext?: CreateContextFn<Router>
|
||||
responseMeta?: ResponseMetaFn<Router>
|
||||
onError?: OnErrorFn<Router>
|
||||
trpcURL: string
|
||||
endpoint: string
|
||||
}) {
|
||||
return defineEventHandler(async (event) => {
|
||||
const {
|
||||
req,
|
||||
res,
|
||||
} = event
|
||||
} = event.node
|
||||
|
||||
const $url = createURL(req.url)
|
||||
const $url = createURL(req.url!)
|
||||
|
||||
const httpResponse = await resolveHTTPResponse({
|
||||
router,
|
||||
req: {
|
||||
method: req.method,
|
||||
method: req.method!,
|
||||
headers: req.headers,
|
||||
body: isMethod(event, 'GET') ? null : await useBody(event),
|
||||
body: isMethod(event, 'GET') ? null : await readBody(event),
|
||||
query: $url.searchParams,
|
||||
},
|
||||
path: $url.pathname.substring(trpcURL.length + 1),
|
||||
path: $url.pathname.substring(endpoint.length + 1),
|
||||
createContext: async () => createContext?.(event),
|
||||
responseMeta,
|
||||
onError: (o) => {
|
||||
@@ -81,8 +81,8 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
||||
|
||||
res.statusCode = status
|
||||
|
||||
Object.keys(headers).forEach((key) => {
|
||||
res.setHeader(key, headers[key])
|
||||
headers && Object.keys(headers).forEach((key) => {
|
||||
res.setHeader(key, headers[key]!)
|
||||
})
|
||||
|
||||
return body
|
||||
|
||||
@@ -8,11 +8,12 @@ import type {
|
||||
import type { ProcedureRecord, inferHandlerInput, inferProcedureInput, inferProcedureOutput } from '@trpc/server'
|
||||
import type { TRPCClient, TRPCClientErrorLike } from '@trpc/client'
|
||||
import { objectHash } from 'ohash'
|
||||
import type { MaybeRef } from '@vueuse/core'
|
||||
import { useStorage } from '@vueuse/core'
|
||||
import { useAsyncData, useNuxtApp, useState } from '#app'
|
||||
import type { Ref } from 'vue'
|
||||
import { useAsyncData, useNuxtApp, useState } from '#imports'
|
||||
import type { router } from '~/server/trpc'
|
||||
|
||||
type MaybeRef<T> = T | Ref<T>
|
||||
|
||||
type AppRouter = typeof router
|
||||
|
||||
export type inferProcedures<
|
||||
@@ -30,12 +31,15 @@ export type TError = TRPCClientErrorLike<AppRouter>
|
||||
export type TQueryValues = inferProcedures<AppRouter['_def']['queries']>
|
||||
|
||||
/**
|
||||
* Additional header properties to pass to tRPC client.
|
||||
*
|
||||
* @see https://trpc.io/docs/vanilla
|
||||
* @param pathAndInput tRPC client path and input.
|
||||
* @param options Options to pass to useAsyncData.
|
||||
* Calculates the key used for `useAsyncData` call
|
||||
* @param pathAndInput
|
||||
*/
|
||||
export function getQueryKey<
|
||||
TPath extends keyof TQueryValues & string,
|
||||
>(pathAndInput: [path: TPath, ...args: inferHandlerInput<TQueries[TPath]>]) {
|
||||
return `${pathAndInput[0]}-${objectHash(pathAndInput[1] ? JSON.stringify(pathAndInput[1]) : '')}`
|
||||
}
|
||||
|
||||
export async function useAsyncQuery<
|
||||
TPath extends keyof TQueryValues & string,
|
||||
TOutput extends TQueryValues[TPath]['output'] = TQueryValues[TPath]['output'],
|
||||
@@ -46,44 +50,22 @@ export async function useAsyncQuery<
|
||||
options: AsyncDataOptions<TOutput, Transform, PickKeys> = {},
|
||||
): Promise<AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, TError>> {
|
||||
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(
|
||||
const key = getQueryKey(pathAndInput)
|
||||
const result = await useAsyncData(
|
||||
key,
|
||||
() => $client.query(...pathAndInput),
|
||||
// @ts-expect-error: Internal
|
||||
options,
|
||||
)
|
||||
|
||||
if (process.server && error.value && !serverError.value)
|
||||
serverError.value = error.value as any
|
||||
|
||||
if (data.value)
|
||||
serverError.value = null
|
||||
|
||||
return {
|
||||
...rest,
|
||||
data,
|
||||
error: serverError,
|
||||
} as any
|
||||
return result as any
|
||||
}
|
||||
|
||||
/**
|
||||
* tRPC Client.
|
||||
*
|
||||
* @see https://trpc.io/docs/vanilla
|
||||
*/
|
||||
export function useClient(): TRPCClient<AppRouter> {
|
||||
const { $client } = useNuxtApp()
|
||||
return $client
|
||||
}
|
||||
|
||||
/**
|
||||
* Additional header properties to pass to tRPC client.
|
||||
*
|
||||
* @see https://github.com/trpc/trpc/discussions/1686
|
||||
* @param initialValue
|
||||
*/
|
||||
export function useClientHeaders(initialValue?: MaybeRef<Record<string, any>>) {
|
||||
return useStorage('trpc-nuxt-header', initialValue || {})
|
||||
export function useClientHeaders(initialValue: MaybeRef<Record<string, any>> = {}): Ref<Record<string, any>> {
|
||||
return useState('trpc-nuxt-header', () => initialValue)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import * as trpc from '@trpc/client'
|
||||
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#app'
|
||||
import { unref } from 'vue'
|
||||
import { FetchError } from 'ofetch'
|
||||
import { useClientHeaders } from './client'
|
||||
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#imports'
|
||||
import type { router } from '~/server/trpc'
|
||||
|
||||
declare type AppRouter = typeof router
|
||||
@@ -7,20 +10,29 @@ declare type AppRouter = typeof router
|
||||
export default defineNuxtPlugin((nuxtApp) => {
|
||||
const config = useRuntimeConfig().public.trpc
|
||||
const headers = useRequestHeaders()
|
||||
const client = trpc.createTRPCClient<AppRouter>({
|
||||
url: `${config.baseURL}${config.trpcURL}`,
|
||||
headers: () => {
|
||||
let otherHeaders = {}
|
||||
if (!process.server) {
|
||||
const key = 'trpc-nuxt-header'
|
||||
otherHeaders = JSON.parse(localStorage.getItem(key) || JSON.stringify({}))
|
||||
}
|
||||
const otherHeaders = useClientHeaders()
|
||||
|
||||
const baseURL = process.server ? '' : config.baseURL
|
||||
const client = trpc.createTRPCClient<AppRouter>({
|
||||
url: `${baseURL}${config.endpoint}`,
|
||||
headers: () => {
|
||||
return {
|
||||
...otherHeaders,
|
||||
...unref(otherHeaders),
|
||||
...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)
|
||||
|
||||
Reference in New Issue
Block a user