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