mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-14 20:19:33 +01:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a53d823f5e | ||
|
|
feef3dde6b | ||
|
|
82ee2ce672 | ||
|
|
f62a13766a | ||
|
|
c7888e81ed | ||
|
|
c77eb68f5d | ||
|
|
333539569c | ||
|
|
e5c40f183b | ||
|
|
273bda980b |
@@ -29,7 +29,7 @@ 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 /api/trpc
|
||||
},
|
||||
typescript: {
|
||||
strict: true // set this to true to make input/output types work
|
||||
@@ -111,7 +111,7 @@ 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
|
||||
// For SSR, please follow this link https://github.com/trpc/trpc/discussions/1686
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "trpc-nuxt",
|
||||
"type": "module",
|
||||
"version": "0.1.24",
|
||||
"version": "0.2.0",
|
||||
"packageManager": "pnpm@7.1.1",
|
||||
"license": "MIT",
|
||||
"main": "./dist/module.cjs",
|
||||
@@ -57,6 +57,9 @@
|
||||
"zod": "^3.16.0"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": "@antfu"
|
||||
"extends": "@antfu",
|
||||
"rules": {
|
||||
"no-console": "warn"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,11 +4,11 @@ import { defu } from 'defu'
|
||||
// @ts-expect-error: No types
|
||||
import dedent from 'dedent'
|
||||
|
||||
import { addPlugin, addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
||||
import { addAutoImport, addPlugin, addServerHandler, addTemplate, defineNuxtModule } from '@nuxt/kit'
|
||||
|
||||
export interface ModuleOptions {
|
||||
baseURL: string
|
||||
trpcURL: string
|
||||
endpoint: string
|
||||
}
|
||||
|
||||
export default defineNuxtModule<ModuleOptions>({
|
||||
@@ -18,7 +18,7 @@ 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))
|
||||
@@ -33,19 +33,17 @@ export default defineNuxtModule<ModuleOptions>({
|
||||
// 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') },
|
||||
)
|
||||
})
|
||||
addAutoImport([
|
||||
{ name: 'useClient', from: join(runtimeDir, 'client') },
|
||||
{ name: 'useAsyncQuery', from: join(runtimeDir, 'client') },
|
||||
{ name: 'useClientHeaders', from: join(runtimeDir, 'client') },
|
||||
])
|
||||
|
||||
addServerHandler({
|
||||
route: `${finalConfig.trpcURL}/*`,
|
||||
route: `${finalConfig.endpoint}/*`,
|
||||
handler: handlerPath,
|
||||
})
|
||||
|
||||
@@ -61,7 +59,7 @@ export default defineNuxtModule<ModuleOptions>({
|
||||
|
||||
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
|
||||
|
||||
@@ -31,6 +31,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'],
|
||||
@@ -41,7 +51,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,
|
||||
|
||||
@@ -11,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