mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 20:19:33 +01:00
Compare commits
81 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
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}}
|
||||
@@ -15,6 +15,8 @@ End-to-end typesafe APIs with [tRPC.io](https://trpc.io/) in Nuxt applications.
|
||||
</figure>
|
||||
</p>
|
||||
|
||||
**⚠️ Currently works on Node v16 until [this issue](https://github.com/trpc/trpc/issues/2420) gets fixed.**
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
@@ -29,10 +31,10 @@ export default defineNuxtConfig({
|
||||
modules: ['trpc-nuxt'],
|
||||
trpc: {
|
||||
baseURL: 'http://localhost:3000', // defaults to http://localhost:3000
|
||||
trpcURL: '/api/trpc', // defaults to /api/trpc
|
||||
endpoint: '/trpc', // defaults to /trpc
|
||||
},
|
||||
typescript: {
|
||||
strict: true // set this to true to make input/output types work
|
||||
strict: true // required to make input/output types work
|
||||
}
|
||||
})
|
||||
```
|
||||
@@ -101,7 +103,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,7 +113,6 @@ 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
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
39
package.json
39
package.json
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "trpc-nuxt",
|
||||
"type": "module",
|
||||
"version": "0.1.18",
|
||||
"packageManager": "pnpm@7.1.1",
|
||||
"version": "0.2.8",
|
||||
"packageManager": "pnpm@7.5.0",
|
||||
"license": "MIT",
|
||||
"main": "./dist/module.cjs",
|
||||
"types": "./dist/types.d.ts",
|
||||
@@ -28,34 +28,39 @@
|
||||
"build:playground": "nuxi build 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"
|
||||
},
|
||||
"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",
|
||||
"@nuxt/kit": "3.0.0-rc.9",
|
||||
"@trpc/client": "^9.27.2",
|
||||
"@trpc/server": "^9.27.2",
|
||||
"dedent": "^0.7.0",
|
||||
"defu": "^6.0.0",
|
||||
"h3": "^0.7.8",
|
||||
"h3": "^0.7.10",
|
||||
"ohash": "^0.1.5",
|
||||
"pathe": "^0.3.0",
|
||||
"ufo": "^0.8.4"
|
||||
"ufo": "^0.8.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^0.23.1",
|
||||
"@antfu/ni": "^0.16.2",
|
||||
"@nuxt/module-builder": "latest",
|
||||
"bumpp": "^7.1.1",
|
||||
"@nuxt/module-builder": "^0.1.7",
|
||||
"@types/dedent": "^0.7.0",
|
||||
"bumpp": "^7.2.0",
|
||||
"eslint": "^8.14.0",
|
||||
"nuxt": "^3.0.0-rc.3",
|
||||
"ohash": "^0.1.0",
|
||||
"pnpm": "^7.1.1",
|
||||
"superjson": "^1.9.1",
|
||||
"nuxt": "3.0.0-rc.9",
|
||||
"pnpm": "^7.5.0",
|
||||
"trpc-nuxt": "workspace:*",
|
||||
"zod": "^3.16.0"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": "@antfu"
|
||||
"extends": "@antfu",
|
||||
"rules": {
|
||||
"no-console": "warn"
|
||||
}
|
||||
},
|
||||
"volta": {
|
||||
"node": "16.14.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ const headers = useClientHeaders()
|
||||
const { data: todos, pending, error, refresh } = await useAsyncQuery(['getTodos'])
|
||||
|
||||
const addHeader = () => {
|
||||
// headers.value.cookie = 'counter=69'
|
||||
headers.value.authorization = 'Bearer abcdefghijklmnop'
|
||||
console.log(headers.value)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ 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'
|
||||
|
||||
@@ -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,
|
||||
|
||||
3652
pnpm-lock.yaml
generated
3652
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,2 +1,2 @@
|
||||
packages:
|
||||
- playground/*
|
||||
- playground
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
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 } from '@nuxt/kit'
|
||||
|
||||
export interface ModuleOptions {
|
||||
baseURL: string
|
||||
trpcURL: string
|
||||
endpoint: string
|
||||
}
|
||||
|
||||
export default defineNuxtModule<ModuleOptions>({
|
||||
@@ -16,34 +17,30 @@ export default defineNuxtModule<ModuleOptions>({
|
||||
},
|
||||
defaults: {
|
||||
baseURL: 'http://localhost:3000',
|
||||
trpcURL: '/api/trpc',
|
||||
endpoint: '/trpc',
|
||||
},
|
||||
async setup(options, nuxt) {
|
||||
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
||||
nuxt.options.build.transpile.push(runtimeDir, '#build/trpc-handler')
|
||||
|
||||
const handlerPath = join(nuxt.options.buildDir, 'trpc-handler.ts')
|
||||
const trpcOptionsPath = join(nuxt.options.rootDir, 'server/trpc')
|
||||
|
||||
// Add vueuse
|
||||
nuxt.options.modules.push('@vueuse/nuxt')
|
||||
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,
|
||||
endpoint: options.endpoint,
|
||||
})
|
||||
|
||||
nuxt.hook('autoImports:extend', (imports) => {
|
||||
imports.push(
|
||||
{ name: 'useClient', from: join(runtimeDir, 'client') },
|
||||
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
||||
{ name: 'useClientHeaders', from: join(runtimeDir, 'client') },
|
||||
)
|
||||
})
|
||||
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({
|
||||
route: `${finalConfig.trpcURL}/*`,
|
||||
route: `${finalConfig.endpoint}/*`,
|
||||
handler: handlerPath,
|
||||
})
|
||||
|
||||
@@ -53,13 +50,13 @@ export default defineNuxtModule<ModuleOptions>({
|
||||
filename: 'trpc-handler.ts',
|
||||
write: true,
|
||||
getContents() {
|
||||
return `
|
||||
return dedent`
|
||||
import { createTRPCHandler } from 'trpc-nuxt/api'
|
||||
import * as functions from '${trpcOptionsPath}'
|
||||
|
||||
export default createTRPCHandler({
|
||||
...functions,
|
||||
trpcURL: '${finalConfig.trpcURL}'
|
||||
endpoint: '${finalConfig.endpoint}'
|
||||
})
|
||||
`
|
||||
},
|
||||
|
||||
@@ -42,13 +42,13 @@ 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 {
|
||||
@@ -56,17 +56,17 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
||||
res,
|
||||
} = event
|
||||
|
||||
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),
|
||||
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 type { Ref } from 'vue'
|
||||
import { useAsyncData, useNuxtApp, useState } from '#app'
|
||||
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,7 +50,7 @@ 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 key = getQueryKey(pathAndInput)
|
||||
const serverError = useState<TError | null>(`error-${key}`, () => null)
|
||||
const { error, data, ...rest } = await useAsyncData(
|
||||
key,
|
||||
@@ -68,22 +72,11 @@ export async function useAsyncQuery<
|
||||
} 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,4 +1,5 @@
|
||||
import * as trpc from '@trpc/client'
|
||||
import { unref } from 'vue'
|
||||
import { useClientHeaders } from './client'
|
||||
import { defineNuxtPlugin, useRequestHeaders, useRuntimeConfig } from '#app'
|
||||
import type { router } from '~/server/trpc'
|
||||
@@ -10,7 +11,7 @@ export default defineNuxtPlugin((nuxtApp) => {
|
||||
const headers = useRequestHeaders()
|
||||
const otherHeaders = useClientHeaders()
|
||||
const client = trpc.createTRPCClient<AppRouter>({
|
||||
url: `${config.baseURL}${config.trpcURL}`,
|
||||
url: `${config.baseURL}${config.endpoint}`,
|
||||
headers: () => {
|
||||
return {
|
||||
...unref(otherHeaders),
|
||||
|
||||
Reference in New Issue
Block a user