Skip to content

Instantly share code, notes, and snippets.

@cj
Created August 23, 2022 03:05
Show Gist options
  • Save cj/6bd9ffee73cf567285034f81c570a465 to your computer and use it in GitHub Desktop.
Save cj/6bd9ffee73cf567285034f81c570a465 to your computer and use it in GitHub Desktop.
Astro trpc client handler
import { appRouter } from 'server'
import type { APIContext } from 'astro'
import { resolveHTTPResponse } from '@trpc/server'
import type { HTTPHeaders } from '@trpc/client'
/**
* Handles trpc query client requests.
*
* @param {APIContext} - Astro API Context
* @returns {Promise<Response>} - trpc response
*
* @beta
*/
async function httpHandler({ request, params }: APIContext): Promise<Response> {
const query = new URL(request.url).searchParams
const requestBody = request.method === 'GET' ? {} : await request.json()
const { status, headers, ...response } = await resolveHTTPResponse({
async createContext() {
// CreateContext
},
router: appRouter,
path: params.trpc as string,
req: {
query,
method: request.method,
headers: request.headers as unknown as HTTPHeaders,
body: requestBody,
},
})
return new Response(response.body, {
headers: headers as HeadersInit,
status,
})
}
export const post = httpHandler
export const get = httpHandler
@cj
Copy link
Author

cj commented Aug 23, 2022

add it to pages/api/trpc/

@cj
Copy link
Author

cj commented Aug 23, 2022

To call it in an Astro page do:

---
import type { AppRouter } from 'server'
import { createTRPCClient } from '@trpc/client'

const client = createTRPCClient<AppRouter>({
  url: `${Astro.url.origin}/api/trpc`,
})

const response = await Promise.all([
  client.query('getUser', 'foobar'),
  client.mutation('createUser', { name: 'testing' }),
])

const [user] = response
---

@Y3K-dev
Copy link

Y3K-dev commented Sep 13, 2022

👀 damn nice, thanks

@frankie-frank-frank
Copy link

which server are you calling AppRouter from?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment