Compare commits

..

134 Commits

Author SHA1 Message Date
wobsoriano
ff4bbebb0b chore: release v0.3.4 2022-12-20 01:34:59 -08:00
wobsoriano
354bf5d707 fix: deprecated h3 properties 2022-12-20 01:34:47 -08:00
wobsoriano
e7d160ee48 fix: client auto-imports 2022-12-20 01:32:59 -08:00
wobsoriano
9bf6d57c2c chore: update deps 2022-12-20 01:14:37 -08:00
Robert Soriano
6bca1e621d Update README.md 2022-11-12 21:18:08 -08:00
wobsoriano
a8e5538b05 release v0.3.3 2022-11-04 07:58:20 -07:00
wobsoriano
24ecb41429 eslint fix 2022-11-04 07:58:16 -07:00
wobsoriano
e8bf427d2b fix types 2022-11-04 07:57:38 -07:00
wobsoriano
347d49482f reinstall deps 2022-11-04 07:55:39 -07:00
wobsoriano
2f7a1276ad feat(deps): bump @nuxt/kit to 3.0.0-rc.13 2022-11-04 07:53:42 -07:00
wobsoriano
f6db0c78cd add .vercel to .gitignore 2022-11-04 07:51:44 -07:00
wobsoriano
d3203f0536 remove docs 2022-11-02 09:43:35 -07:00
wobsoriano
83e2b2810d release v0.3.2 2022-11-02 09:42:08 -07:00
wobsoriano
2b4fff9faa feat(deps): bump h3 to 0.8.6 2022-11-02 09:41:39 -07:00
wobsoriano
752fe721a2 feat(deps): lock @trpc/server and @trpc/client to version 9 2022-11-02 09:40:48 -07:00
wobsoriano
808cac4756 eslint fixes 2022-11-02 09:38:14 -07:00
wobsoriano
0c44f73c9f log info about plugin installation 2022-11-02 09:34:16 -07:00
wobsoriano
182875a781 feat: add option to specify if plugin should be installed 2022-11-02 09:30:40 -07:00
wobsoriano
0298f836b8 more eslint fixes 2022-11-02 09:21:15 -07:00
wobsoriano
ea50430945 eslint fixes 2022-11-02 09:18:17 -07:00
wobsoriano
0e240663ca remove local pnpm deps 2022-11-02 09:18:00 -07:00
Robert Soriano
bdeada0e6e Merge pull request #32 from littlejon85/9-server-error-discard
fix: don't discard error in client
2022-10-28 14:53:09 -07:00
Robert Soriano
fd9b86fb18 release v0.3.1 2022-10-21 12:27:16 -07:00
Robert Soriano
5fab0e54b0 update local deps 2022-10-21 12:24:18 -07:00
Robert Soriano
7d2f464699 Merge pull request #34 from mahdiboomeri/chore
chore: bump nuxt to RC 12
2022-10-21 08:10:53 -07:00
Mahdi Boomeri
fdb9c2b474 refactor: playground nuxt.config 2022-10-21 17:00:22 +03:30
Mahdi Boomeri
4ed504e1e9 fix: h3 CompatibilityEvent 2022-10-21 16:56:09 +03:30
Mahdi Boomeri
92747711c6 chore: bump other deps 2022-10-21 16:53:53 +03:30
Mahdi Boomeri
3646e8cdfe chore: nump nuxt 2022-10-21 16:43:22 +03:30
Jan Dlouhý
88214185a8 fix: use useAsyncData error in client 2022-10-15 22:36:28 +02:00
Jan Dlouhý
ad03ae7b65 fix: don't discard error in client 2022-10-11 14:35:21 +02:00
Robert Soriano
09e8ab536a feat: replace useBody with readBody 2022-10-01 09:15:36 -07:00
Robert Soriano
f7dadd482d Update README.md 2022-09-29 10:20:05 -07:00
Robert Soriano
7b69cff1ed Merge pull request #30 from cawa-93/patch-1
docs: Fix `baseURL` in code sample
2022-09-27 10:18:15 -07:00
Alex Kozack
f2d7763fa4 docs: Fix baseURL in code sample 2022-09-27 10:41:38 +03:00
Robert Soriano
20f5a08cbd update readme 2022-09-24 08:26:36 -07:00
Robert Soriano
75980c0953 release v0.3.0 2022-09-24 08:25:33 -07:00
Robert Soriano
a6f61d404f feat(deps): bump h3 to 0.7.21 2022-09-24 08:24:57 -07:00
Robert Soriano
e53d1be61e feat(deps): bump @nuxt/kit to 3.0.0-rc-11 2022-09-24 08:23:29 -07:00
Robert Soriano
d152ebc7be chore: remove volta config 2022-09-24 08:20:24 -07:00
Robert Soriano
f6daa2b7c3 Merge pull request #28 from robinWongM/feature/direct-api-call-during-ssr
feat: use globalThis.$fetch to call API handler directly on server-side
2022-09-24 08:19:16 -07:00
Robin Wong
7962c7f61e fix: return original FetchResponse when ohmyfetch throws error 2022-09-18 09:46:59 +00:00
Robin Wong
453845fb14 fix: eslint errors 2022-09-18 08:44:43 +00:00
Robin Wong
ee3ee485ba feat: use globalThis.$fetch to call API handler directly on server-side 2022-09-16 16:53:15 +00:00
Robert Soriano
cdf29bee67 release v0.2.8 2022-09-08 09:36:32 -07:00
Robert Soriano
d3d35404b1 update release script 2022-09-08 09:36:24 -07:00
Robert Soriano
e57c919157 Merge pull request #26 from elfpie/feature/update-nuxt
Bump nuxt to RC9
2022-09-08 08:11:24 -07:00
Felipe
d0fffbbc64 feat(deps): bump nuxt to 3.0.0-rc.9 2022-09-07 17:59:23 -03:00
Felipe
433d5ada46 feat(deps): bump @trpc/client to 9.27.2 2022-09-07 17:59:23 -03:00
Felipe
5d180460af feat(deps): bump @trpc/server to 9.27.2 2022-09-07 17:59:23 -03:00
Felipe
8991148d39 feat(deps): bump @nuxt/kit to 3.0.0-rc.9 2022-09-07 17:59:15 -03:00
Robert Soriano
dd05285d65 release v0.2.7 2022-08-31 12:10:12 -07:00
Robert Soriano
d058ff241a update playground 2022-08-31 12:09:45 -07:00
Robert Soriano
fb4894e264 Merge pull request #25 from mahdiboomeri/fix/useClientHeaders
Fix useClientHeaders
2022-08-31 12:07:05 -07:00
Mahdi Boomeri
186faff140 docs: replaced useStorage with useState in useClientHeaders 2022-08-31 19:19:27 +04:30
Mahdi Boomeri
b9cdb228b7 refactor: remove vueuse dependency 2022-08-31 19:17:44 +04:30
Mahdi Boomeri
1e67434a8f fix: useClientHeaders returning an empty object 2022-08-31 19:13:29 +04:30
Robert Soriano
019bb20e50 release v0.2.6 2022-08-20 00:10:00 -07:00
Robert Soriano
695ce4c56e feat(deps): bump @trpc/server from 9.27.0 to 9.27.1 2022-08-20 00:09:39 -07:00
Robert Soriano
38649b7023 feat(deps): bump @trpc/client from 9.27.0 to 9.27.1 2022-08-20 00:09:17 -07:00
Robert Soriano
5cfef32baa release v0.2.5 2022-08-14 12:38:56 -07:00
Robert Soriano
8497289c65 update readme 2022-08-14 12:38:31 -07:00
Robert Soriano
224c4b317b move ohash to deps 2022-08-14 12:29:04 -07:00
Robert Soriano
d5d6780ca8 bump ohash 2022-08-14 12:28:03 -07:00
Robert Soriano
252d0f6692 feat(deps): bump vueuse from 8.9.3 to 9.1.0 2022-08-14 12:27:10 -07:00
Robert Soriano
d022710591 bump dev deps 2022-08-14 12:26:33 -07:00
Robert Soriano
a926968f13 feat(deps): bump @nuxt/kit from 3.0.0-rc.5 to 3.0.0-rc.8 2022-08-14 12:25:48 -07:00
Robert Soriano
a8eba5ab8d feat(deps): bump @trpc/server from 9.26.0 to 9.27.0 2022-08-14 12:25:14 -07:00
Robert Soriano
5871528d67 feat(deps): bump @trpc/client from 9.26.0 to 9.27.0 2022-08-14 12:24:52 -07:00
Robert Soriano
def9d0b19d volta pin node@16 2022-08-14 12:24:20 -07:00
Robert Soriano
34f50fc4d6 chore(deps): bump pnpm to 7.5.0 2022-07-14 19:04:19 -07:00
Robert Soriano
9fe1469eba release v0.2.4 2022-07-14 19:03:09 -07:00
Robert Soriano
e48d7cd42c feat(deps): bump @nuxt/kit from 3.0.0-rc.4 to 3.0.0-rc.5 2022-07-14 19:02:54 -07:00
Robert Soriano
2b517ad77b release v0.2.3 2022-07-14 11:19:28 -07:00
Robert Soriano
77ee994e13 update deps 2022-07-14 11:19:19 -07:00
Robert Soriano
67a8a2a3ed feat(deps): bump ufo from 0.8.4 to 0.8.5 2022-07-14 11:19:01 -07:00
Robert Soriano
556b5c8e08 feat(deps): bump @vueuse/nuxt from 8.7.4 to 8.9.3 2022-07-14 11:18:37 -07:00
Robert Soriano
85154f12d7 feat(deps): bump @vueuse/core from 8.7.4 to 8.9.3 2022-07-14 11:18:21 -07:00
Robert Soriano
26ce46e12b feat(deps): bump @trpc/server from 9.25.3 to 9.26.0 2022-07-14 11:17:51 -07:00
Robert Soriano
c2cfd9a214 feat(deps): bump @trpc/client from 9.25.3 to 9.26.0 2022-07-14 11:17:34 -07:00
Robert Soriano
f736545128 ci: add release workflow 2022-07-14 11:16:43 -07:00
Robert Soriano
59a9eb5f95 fix playground workspace 2022-07-05 20:24:40 -07:00
Robert Soriano
48fc19076f Update README.md 2022-06-23 10:03:48 -07:00
Robert Soriano
6b83e5d4ea chore(deps): bump @trpc/server to 9.25.3 2022-06-18 21:06:25 -07:00
Robert Soriano
0358a258d7 chore(deps): bump @trpc/client to 9.25.3 2022-06-18 21:06:11 -07:00
Robert Soriano
8e7f33c9d2 chore(deps): bump h3 to 0.7.10 2022-06-18 21:05:48 -07:00
Robert Soriano
b8f4af2df3 chore(deps): bump @vueuse/nuxt to 8.7.4 2022-06-18 21:05:15 -07:00
Robert Soriano
666751678c chore(deps): bump @vueuse/core to 8.7.4 2022-06-18 21:04:56 -07:00
Robert Soriano
cab89aaa66 chore(deps): bump bumpp to 7.2.0 2022-06-18 21:04:17 -07:00
Robert Soriano
4c9850fafc chore(deps): add @types/dedent 2022-06-18 21:02:44 -07:00
Robert Soriano
07693009f8 release v0.2.2 2022-06-16 06:49:32 -07:00
Robert Soriano
dceade155c chore(deps): bump nuxt to 3.0.0-rc.4 2022-06-16 06:48:56 -07:00
Robert Soriano
4012249f09 chore(deps): bump h3 to 0.7.9 2022-06-16 06:48:20 -07:00
Robert Soriano
38eda2c4d6 chore(deps): bump @trpc/client to 9.25.2 2022-06-16 06:47:39 -07:00
Robert Soriano
9468af75f4 chore(deps): bump @trpc/server to 9.25.2 2022-06-16 06:47:18 -07:00
Robert Soriano
ea24a67a6d chore(deps): bump @nuxt/kit to 3.0.0-rc.4 2022-06-16 06:46:35 -07:00
Robert Soriano
5e8d04741c release v0.2.1 2022-06-13 18:51:41 -07:00
Robert Soriano
1032e65a0d refactor: remove unused import in playground 2022-06-13 18:51:35 -07:00
Robert Soriano
f261d3feeb Merge pull request #12 from cawa-93/patch-1
fix: auto-import `getQueryKey`
2022-06-13 18:49:07 -07:00
Alex Kozack
b1ca09e986 fix: auto-import getQueryKey 2022-06-13 12:06:03 +03:00
Robert Soriano
b804429fc0 update readme 2022-06-12 23:32:55 -07:00
Robert Soriano
7df64296ff update readme 2022-06-12 23:32:41 -07:00
Robert Soriano
a53d823f5e release v0.2.0 2022-06-12 23:30:07 -07:00
Robert Soriano
feef3dde6b update readme 2022-06-12 23:30:03 -07:00
Robert Soriano
82ee2ce672 refactor!: replace trpcURL option with endpoint 2022-06-12 23:29:28 -07:00
Robert Soriano
f62a13766a update readme 2022-06-12 23:19:55 -07:00
Robert Soriano
c7888e81ed refactor: use addAutoImport 2022-06-12 23:18:38 -07:00
Robert Soriano
c77eb68f5d refactor: rename endpoint option 2022-06-12 23:17:13 -07:00
Robert Soriano
333539569c refactor: lint 2022-06-12 23:16:01 -07:00
Robert Soriano
e5c40f183b Merge pull request #7 from cawa-93/feat/extract-get-query-key
feat: extract `getQueryKey` helper
2022-06-12 23:08:21 -07:00
Robert Soriano
977a9e1465 release v0.1.24 2022-06-05 17:05:34 -07:00
Robert Soriano
2620379e02 feat: allow changing of src dir 2022-06-05 17:05:13 -07:00
Robert Soriano
e4f42d5322 Merge pull request #10 from nicolesmileyface/feat/support-src-dir
use nuxt srcDir instead of rootDir
2022-06-05 17:02:41 -07:00
Cole Hollant
ad28a9124e use nuxt srcDir instead of rootDir 2022-06-05 11:55:25 -04:00
cawa-93
273bda980b feat: extract getQueryKey helper
This method will be useful to get a key that can be used to reset the internal nuxt cache
2022-05-31 15:20:21 +03:00
Robert Soriano
9c8509f79c release v0.1.23 2022-05-27 08:53:18 -07:00
Robert Soriano
2ce29137ce fix: unimported composable 2022-05-27 08:41:14 -07:00
Robert Soriano
e9c5307e23 release v0.1.22 2022-05-27 01:10:10 -07:00
Robert Soriano
bbdabf544c fix: type inference bug with vueuse 2022-05-27 01:10:06 -07:00
Robert Soriano
aed10ac5b8 release v0.1.21 2022-05-27 00:56:58 -07:00
Robert Soriano
4b2c714658 fix: remove module export 2022-05-27 00:56:53 -07:00
Robert Soriano
43e9fefdbd release v0.1.20 2022-05-26 13:48:57 -07:00
Robert Soriano
dabda23976 export module id 2022-05-26 13:48:53 -07:00
Robert Soriano
af89f32275 release v0.1.19 2022-05-26 07:27:20 -07:00
Robert Soriano
1f27b871fb fix: unref import from vue 2022-05-26 07:21:42 -07:00
Robert Soriano
281e4c05a0 release v0.1.18 2022-05-24 10:01:23 -07:00
Robert Soriano
38ac520b97 fix: server storage and incorrect imports 2022-05-24 10:01:19 -07:00
Robert Soriano
96ebff619e release v0.1.17 2022-05-24 09:55:59 -07:00
Robert Soriano
f668e4a9b4 docs: update readme 2022-05-24 09:55:35 -07:00
Robert Soriano
58b0165557 update readme 2022-05-24 09:55:05 -07:00
Robert Soriano
3b5e35ef68 feat: add composable for custom client headers 2022-05-24 09:46:15 -07:00
Robert Soriano
48152ead8d refactor: remove some comments 2022-05-24 06:43:42 -07:00
Robert Soriano
7f44e049c0 release v0.1.16 2022-05-23 12:41:55 -07:00
Robert Soriano
5a71bbf1fe refactor: use trpc url from config 2022-05-23 12:41:49 -07:00
17 changed files with 2308 additions and 2610 deletions

22
.github/workflows/release.yml vendored Normal file
View 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
View File

@@ -49,3 +49,5 @@ coverage
Network Trash Folder
Temporary Items
.apdisk
.vercel

2
.nuxtrc Normal file
View File

@@ -0,0 +1,2 @@
imports.autoImport=false
typescript.includeWorkspace=true

View File

@@ -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
}
})
```
@@ -99,6 +100,22 @@ const {
})
```
## useClientHeaders
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()
const { data: token } = await useAsyncQuery(['auth.login', { username, password }])
headers.value.Authorization = `Bearer ${token}`
// 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
trpc-nuxt accepts the following options exposed under `~/server/trpc/index.ts`:
@@ -106,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 */
@@ -145,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

View File

@@ -1,20 +1,19 @@
{
"name": "trpc-nuxt",
"type": "module",
"version": "0.1.15",
"packageManager": "pnpm@7.1.1",
"version": "0.3.4",
"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"
}
},
"files": [
@@ -22,38 +21,44 @@
"*.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",
"release": "bumpp --commit --push --tag && npm publish",
"prepare": "nuxi prepare playground"
},
"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",
"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",
"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"
}
}
}

View File

@@ -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: '',
},
})

View File

@@ -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>

View File

@@ -1,12 +1,19 @@
<script setup lang="ts">
const { $client } = useNuxtApp()
import { useClient, useClientHeaders, useAsyncQuery } from '#imports'
const client = useClient()
const headers = useClientHeaders()
const { data: todos, pending, error, refresh } = await useAsyncQuery(['getTodos'])
const addHeader = () => {
headers.value.authorization = 'Bearer abcdefghijklmnop'
console.log(headers.value)
}
const addTodo = async () => {
const title = Math.random().toString(36).slice(2, 7)
try {
const result = await $client.mutation('addTodo', {
const result = await client.mutation('addTodo', {
id: Date.now(),
userId: 69,
title,
@@ -27,7 +34,7 @@ const addTodo = async () => {
<div v-else-if="error?.data?.code">
Error: {{ error.data.code }}
</div>
<div v-else>
<div v-else-if="todos">
<ul>
<li v-for="t in todos.slice(0, 10)" :key="t.id">
<NuxtLink :class="{ completed: t.completed }" :to="`/todo/${t.id}`">
@@ -41,6 +48,9 @@ const addTodo = async () => {
<button @click="() => refresh()">
Refresh
</button>
<button @click="addHeader">
Add header
</button>
</div>
</template>

View File

@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useRoute, useAsyncQuery } 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>

View File

@@ -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'
@@ -30,6 +29,7 @@ export const router = trpc.router<Context>()
.mutation('addTodo', {
input: TodoShape,
async resolve(req) {
console.log(req.input)
return await $fetch<Todo>(`${baseURL}/todos`, {
method: 'POST',
body: req.input,
@@ -37,13 +37,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(x)
// const x = useCookies(event)
console.log(event.req.headers)
return {

4575
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,2 +1,2 @@
packages:
- playground/*
- playground

View File

@@ -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

View File

@@ -1,68 +1,80 @@
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 logger = useLogger(metaName)
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
nuxt.options.build.transpile.push(runtimeDir, '#build/trpc-handler')
nuxt.options.build.transpile.push(runtimeDir)
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')
// 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') },
)
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 { useRuntimeConfig } from '#imports'
return dedent`
import { createTRPCHandler } from ${JSON.stringify(join(runtimeDir, 'api'))}
import * as functions from '${trpcOptionsPath}'
const { trpc: { trpcURL } } = useRuntimeConfig().public
export default createTRPCHandler({
...functions,
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.')
}
},
})

View File

@@ -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

View File

@@ -8,10 +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 { Ref } from 'vue'
import { useAsyncData, useNuxtApp, useState } from '#app'
// @ts-expect-error: Resolved by Nuxt
import type { router } from '~/server/trpc'
type MaybeRef<T> = T | Ref<T>
type AppRouter = typeof router
export type inferProcedures<
@@ -28,6 +30,16 @@ export type TError = TRPCClientErrorLike<AppRouter>
export type TQueryValues = inferProcedures<AppRouter['_def']['queries']>
/**
* 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'],
@@ -38,28 +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
}
export function useClient(): TRPCClient<AppRouter> {
const { $client } = useNuxtApp()
return $client
}
export function useClientHeaders(initialValue: MaybeRef<Record<string, any>> = {}): Ref<Record<string, any>> {
return useState('trpc-nuxt-header', () => initialValue)
}

View File

@@ -1,22 +1,41 @@
import * as trpc from '@trpc/client'
// @ts-expect-error: Resolved by Nuxt
import { unref } from 'vue'
import { FetchError } from 'ohmyfetch'
import { useClientHeaders } from './client'
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#app'
import type { router } from '~/server/trpc'
declare type AppRouter = typeof router
export default defineNuxtPlugin(() => {
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig().public.trpc
const headers = useRequestHeaders()
const otherHeaders = useClientHeaders()
const baseURL = process.server ? '' : config.baseURL
const client = trpc.createTRPCClient<AppRouter>({
url: `${config.baseURL}${config.trpcURL}`,
headers: useRequestHeaders(),
url: `${baseURL}${config.endpoint}`,
headers: () => {
return {
...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),
})),
})
return {
provide: {
client,
},
}
nuxtApp.provide('client', client)
})
declare module '#app' {