mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-23 16:30:41 +01:00
Compare commits
50 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
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}}
|
||||||
@@ -29,10 +29,10 @@ export default defineNuxtConfig({
|
|||||||
modules: ['trpc-nuxt'],
|
modules: ['trpc-nuxt'],
|
||||||
trpc: {
|
trpc: {
|
||||||
baseURL: 'http://localhost:3000', // defaults to http://localhost:3000
|
baseURL: 'http://localhost:3000', // defaults to http://localhost:3000
|
||||||
trpcURL: '/api/trpc', // defaults to /api/trpc
|
endpoint: '/trpc', // defaults to /trpc
|
||||||
},
|
},
|
||||||
typescript: {
|
typescript: {
|
||||||
strict: true // set this to true to make input/output types work
|
strict: true // required to make input/output types work
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
@@ -111,7 +111,6 @@ const { data: token } = await useAsyncQuery(['auth.login', { username, password
|
|||||||
headers.value.Authorization = `Bearer ${token}`
|
headers.value.Authorization = `Bearer ${token}`
|
||||||
|
|
||||||
// All client calls will now include the Authorization header.
|
// 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
|
## Options
|
||||||
|
|||||||
28
package.json
28
package.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "trpc-nuxt",
|
"name": "trpc-nuxt",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"version": "0.1.19",
|
"version": "0.2.3",
|
||||||
"packageManager": "pnpm@7.1.1",
|
"packageManager": "pnpm@7.1.1",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"main": "./dist/module.cjs",
|
"main": "./dist/module.cjs",
|
||||||
@@ -32,30 +32,34 @@
|
|||||||
"prepare": "nuxi prepare playground"
|
"prepare": "nuxi prepare playground"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nuxt/kit": "^3.0.0-rc.3",
|
"@nuxt/kit": "^3.0.0-rc.4",
|
||||||
"@trpc/client": "^9.23.3",
|
"@trpc/client": "^9.26.0",
|
||||||
"@trpc/server": "^9.23.2",
|
"@trpc/server": "^9.26.0",
|
||||||
"@vueuse/core": "^8.5.0",
|
"@vueuse/core": "^8.9.3",
|
||||||
"@vueuse/nuxt": "^8.5.0",
|
"@vueuse/nuxt": "^8.9.3",
|
||||||
|
"dedent": "^0.7.0",
|
||||||
"defu": "^6.0.0",
|
"defu": "^6.0.0",
|
||||||
"h3": "^0.7.8",
|
"h3": "^0.7.10",
|
||||||
"pathe": "^0.3.0",
|
"pathe": "^0.3.0",
|
||||||
"ufo": "^0.8.4"
|
"ufo": "^0.8.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@antfu/eslint-config": "^0.23.1",
|
"@antfu/eslint-config": "^0.23.1",
|
||||||
"@antfu/ni": "^0.16.2",
|
"@antfu/ni": "^0.16.2",
|
||||||
"@nuxt/module-builder": "latest",
|
"@nuxt/module-builder": "latest",
|
||||||
"bumpp": "^7.1.1",
|
"@types/dedent": "^0.7.0",
|
||||||
|
"bumpp": "^7.2.0",
|
||||||
"eslint": "^8.14.0",
|
"eslint": "^8.14.0",
|
||||||
"nuxt": "^3.0.0-rc.3",
|
"nuxt": "3.0.0-rc.4",
|
||||||
"ohash": "^0.1.0",
|
"ohash": "^0.1.0",
|
||||||
"pnpm": "^7.1.1",
|
"pnpm": "^7.1.1",
|
||||||
"superjson": "^1.9.1",
|
|
||||||
"trpc-nuxt": "workspace:*",
|
"trpc-nuxt": "workspace:*",
|
||||||
"zod": "^3.16.0"
|
"zod": "^3.16.0"
|
||||||
},
|
},
|
||||||
"eslintConfig": {
|
"eslintConfig": {
|
||||||
"extends": "@antfu"
|
"extends": "@antfu",
|
||||||
|
"rules": {
|
||||||
|
"no-console": "warn"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ 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 { CompatibilityEvent } from 'h3'
|
||||||
import { useCookies } from 'h3'
|
|
||||||
|
|
||||||
const baseURL = 'https://jsonplaceholder.typicode.com'
|
const baseURL = 'https://jsonplaceholder.typicode.com'
|
||||||
|
|
||||||
@@ -30,6 +29,7 @@ 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,
|
||||||
|
|||||||
2270
pnpm-lock.yaml
generated
2270
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,2 +1,2 @@
|
|||||||
packages:
|
packages:
|
||||||
- playground/*
|
- playground
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { fileURLToPath } from 'url'
|
import { fileURLToPath } from 'url'
|
||||||
import { join, resolve } from 'pathe'
|
import { join, resolve } from 'pathe'
|
||||||
import { defu } from 'defu'
|
import { defu } from 'defu'
|
||||||
|
import dedent from 'dedent'
|
||||||
|
|
||||||
import { addPlugin, addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
import { addAutoImport, addPlugin, addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
||||||
|
|
||||||
export interface ModuleOptions {
|
export interface ModuleOptions {
|
||||||
baseURL: string
|
baseURL: string
|
||||||
trpcURL: string
|
endpoint: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export default defineNuxtModule<ModuleOptions>({
|
export default defineNuxtModule<ModuleOptions>({
|
||||||
@@ -16,14 +17,14 @@ export default defineNuxtModule<ModuleOptions>({
|
|||||||
},
|
},
|
||||||
defaults: {
|
defaults: {
|
||||||
baseURL: 'http://localhost:3000',
|
baseURL: 'http://localhost:3000',
|
||||||
trpcURL: '/api/trpc',
|
endpoint: '/trpc',
|
||||||
},
|
},
|
||||||
async setup(options, nuxt) {
|
async setup(options, nuxt) {
|
||||||
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
|
||||||
nuxt.options.build.transpile.push(runtimeDir, '#build/trpc-handler')
|
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.rootDir, 'server/trpc')
|
const trpcOptionsPath = join(nuxt.options.srcDir, 'server/trpc')
|
||||||
|
|
||||||
// Add vueuse
|
// Add vueuse
|
||||||
nuxt.options.modules.push('@vueuse/nuxt')
|
nuxt.options.modules.push('@vueuse/nuxt')
|
||||||
@@ -31,19 +32,18 @@ export default defineNuxtModule<ModuleOptions>({
|
|||||||
// 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,
|
||||||
trpcURL: options.trpcURL,
|
endpoint: options.endpoint,
|
||||||
})
|
})
|
||||||
|
|
||||||
nuxt.hook('autoImports:extend', (imports) => {
|
addAutoImport([
|
||||||
imports.push(
|
{ name: 'useClient', from: join(runtimeDir, 'client') },
|
||||||
{ name: 'useClient', from: join(runtimeDir, 'client') },
|
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
||||||
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
{ name: 'useClientHeaders', from: join(runtimeDir, 'client') },
|
||||||
{ name: 'useClientHeaders', from: join(runtimeDir, 'client') },
|
{ name: 'getQueryKey', from: join(runtimeDir, 'client') },
|
||||||
)
|
])
|
||||||
})
|
|
||||||
|
|
||||||
addServerHandler({
|
addServerHandler({
|
||||||
route: `${finalConfig.trpcURL}/*`,
|
route: `${finalConfig.endpoint}/*`,
|
||||||
handler: handlerPath,
|
handler: handlerPath,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -53,13 +53,13 @@ export default defineNuxtModule<ModuleOptions>({
|
|||||||
filename: 'trpc-handler.ts',
|
filename: 'trpc-handler.ts',
|
||||||
write: true,
|
write: true,
|
||||||
getContents() {
|
getContents() {
|
||||||
return `
|
return dedent`
|
||||||
import { createTRPCHandler } from 'trpc-nuxt/api'
|
import { createTRPCHandler } from 'trpc-nuxt/api'
|
||||||
import * as functions from '${trpcOptionsPath}'
|
import * as functions from '${trpcOptionsPath}'
|
||||||
|
|
||||||
export default createTRPCHandler({
|
export default createTRPCHandler({
|
||||||
...functions,
|
...functions,
|
||||||
trpcURL: '${finalConfig.trpcURL}'
|
endpoint: '${finalConfig.endpoint}'
|
||||||
})
|
})
|
||||||
`
|
`
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -42,13 +42,13 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
|||||||
createContext,
|
createContext,
|
||||||
responseMeta,
|
responseMeta,
|
||||||
onError,
|
onError,
|
||||||
trpcURL,
|
endpoint,
|
||||||
}: {
|
}: {
|
||||||
router: Router
|
router: Router
|
||||||
createContext?: CreateContextFn<Router>
|
createContext?: CreateContextFn<Router>
|
||||||
responseMeta?: ResponseMetaFn<Router>
|
responseMeta?: ResponseMetaFn<Router>
|
||||||
onError?: OnErrorFn<Router>
|
onError?: OnErrorFn<Router>
|
||||||
trpcURL: string
|
endpoint: string
|
||||||
}) {
|
}) {
|
||||||
return defineEventHandler(async (event) => {
|
return defineEventHandler(async (event) => {
|
||||||
const {
|
const {
|
||||||
@@ -56,17 +56,17 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
|||||||
res,
|
res,
|
||||||
} = event
|
} = event
|
||||||
|
|
||||||
const $url = createURL(req.url)
|
const $url = createURL(req.url!)
|
||||||
|
|
||||||
const httpResponse = await resolveHTTPResponse({
|
const httpResponse = await resolveHTTPResponse({
|
||||||
router,
|
router,
|
||||||
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 useBody(event),
|
||||||
query: $url.searchParams,
|
query: $url.searchParams,
|
||||||
},
|
},
|
||||||
path: $url.pathname.substring(trpcURL.length + 1),
|
path: $url.pathname.substring(endpoint.length + 1),
|
||||||
createContext: async () => createContext?.(event),
|
createContext: async () => createContext?.(event),
|
||||||
responseMeta,
|
responseMeta,
|
||||||
onError: (o) => {
|
onError: (o) => {
|
||||||
@@ -81,8 +81,8 @@ export function createTRPCHandler<Router extends AnyRouter>({
|
|||||||
|
|
||||||
res.statusCode = status
|
res.statusCode = status
|
||||||
|
|
||||||
Object.keys(headers).forEach((key) => {
|
headers && Object.keys(headers).forEach((key) => {
|
||||||
res.setHeader(key, headers[key])
|
res.setHeader(key, headers[key]!)
|
||||||
})
|
})
|
||||||
|
|
||||||
return body
|
return body
|
||||||
|
|||||||
@@ -8,11 +8,13 @@ import type {
|
|||||||
import type { ProcedureRecord, inferHandlerInput, inferProcedureInput, inferProcedureOutput } from '@trpc/server'
|
import type { ProcedureRecord, inferHandlerInput, inferProcedureInput, inferProcedureOutput } from '@trpc/server'
|
||||||
import type { TRPCClient, TRPCClientErrorLike } from '@trpc/client'
|
import type { TRPCClient, TRPCClientErrorLike } from '@trpc/client'
|
||||||
import { objectHash } from 'ohash'
|
import { objectHash } from 'ohash'
|
||||||
import type { MaybeRef } from '@vueuse/core'
|
import type { Ref } from 'vue'
|
||||||
import { useStorage } from '@vueuse/core'
|
import { useStorage } from '@vueuse/core'
|
||||||
import { useAsyncData, useNuxtApp, useState } from '#app'
|
import { useAsyncData, useNuxtApp, useState } from '#app'
|
||||||
import type { router } from '~/server/trpc'
|
import type { router } from '~/server/trpc'
|
||||||
|
|
||||||
|
type MaybeRef<T> = T | Ref<T>
|
||||||
|
|
||||||
type AppRouter = typeof router
|
type AppRouter = typeof router
|
||||||
|
|
||||||
export type inferProcedures<
|
export type inferProcedures<
|
||||||
@@ -30,12 +32,15 @@ export type TError = TRPCClientErrorLike<AppRouter>
|
|||||||
export type TQueryValues = inferProcedures<AppRouter['_def']['queries']>
|
export type TQueryValues = inferProcedures<AppRouter['_def']['queries']>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Additional header properties to pass to tRPC client.
|
* Calculates the key used for `useAsyncData` call
|
||||||
*
|
* @param pathAndInput
|
||||||
* @see https://trpc.io/docs/vanilla
|
|
||||||
* @param pathAndInput tRPC client path and input.
|
|
||||||
* @param options Options to pass to useAsyncData.
|
|
||||||
*/
|
*/
|
||||||
|
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<
|
export async function useAsyncQuery<
|
||||||
TPath extends keyof TQueryValues & string,
|
TPath extends keyof TQueryValues & string,
|
||||||
TOutput extends TQueryValues[TPath]['output'] = TQueryValues[TPath]['output'],
|
TOutput extends TQueryValues[TPath]['output'] = TQueryValues[TPath]['output'],
|
||||||
@@ -46,7 +51,7 @@ export async function useAsyncQuery<
|
|||||||
options: AsyncDataOptions<TOutput, Transform, PickKeys> = {},
|
options: AsyncDataOptions<TOutput, Transform, PickKeys> = {},
|
||||||
): Promise<AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, TError>> {
|
): Promise<AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, TError>> {
|
||||||
const { $client } = useNuxtApp()
|
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 serverError = useState<TError | null>(`error-${key}`, () => null)
|
||||||
const { error, data, ...rest } = await useAsyncData(
|
const { error, data, ...rest } = await useAsyncData(
|
||||||
key,
|
key,
|
||||||
@@ -68,22 +73,11 @@ export async function useAsyncQuery<
|
|||||||
} as any
|
} as any
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* tRPC Client.
|
|
||||||
*
|
|
||||||
* @see https://trpc.io/docs/vanilla
|
|
||||||
*/
|
|
||||||
export function useClient(): TRPCClient<AppRouter> {
|
export function useClient(): TRPCClient<AppRouter> {
|
||||||
const { $client } = useNuxtApp()
|
const { $client } = useNuxtApp()
|
||||||
return $client
|
return $client
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export function useClientHeaders(initialValue: MaybeRef<Record<string, any>> = {}): Ref<Record<string, any>> {
|
||||||
* Additional header properties to pass to tRPC client.
|
return useStorage('trpc-nuxt-header', initialValue)
|
||||||
*
|
|
||||||
* @see https://github.com/trpc/trpc/discussions/1686
|
|
||||||
* @param initialValue
|
|
||||||
*/
|
|
||||||
export function useClientHeaders(initialValue?: MaybeRef<Record<string, any>>) {
|
|
||||||
return useStorage('trpc-nuxt-header', initialValue || {})
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ export default defineNuxtPlugin((nuxtApp) => {
|
|||||||
const headers = useRequestHeaders()
|
const headers = useRequestHeaders()
|
||||||
const otherHeaders = useClientHeaders()
|
const otherHeaders = useClientHeaders()
|
||||||
const client = trpc.createTRPCClient<AppRouter>({
|
const client = trpc.createTRPCClient<AppRouter>({
|
||||||
url: `${config.baseURL}${config.trpcURL}`,
|
url: `${config.baseURL}${config.endpoint}`,
|
||||||
headers: () => {
|
headers: () => {
|
||||||
return {
|
return {
|
||||||
...unref(otherHeaders),
|
...unref(otherHeaders),
|
||||||
|
|||||||
Reference in New Issue
Block a user