Compare commits

...

9 Commits

Author SHA1 Message Date
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
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
6 changed files with 37 additions and 26 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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