From deea70b74318cb0ea20d42da7865761d6b336c70 Mon Sep 17 00:00:00 2001 From: Robert Soriano Date: Sun, 30 Oct 2022 18:17:14 -0700 Subject: [PATCH] check trpc path via h3 context params --- src/server.ts | 44 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/src/server.ts b/src/server.ts index 09a15c5..f31c969 100644 --- a/src/server.ts +++ b/src/server.ts @@ -3,13 +3,15 @@ import { resolveHTTPResponse } from '@trpc/server/http' import type { AnyRouter, ProcedureType, - TRPCError, inferRouterContext, inferRouterError, } from '@trpc/server' +import { + TRPCError, +} from '@trpc/server' import { createURL } from 'ufo' import type { H3Event } from 'h3' -import { defineEventHandler, isMethod, readBody } from 'h3' +import { defineEventHandler, isMethod, readBody, createError } from 'h3' import type { TRPCResponse } from '@trpc/server/rpc' type MaybePromise = T | Promise @@ -37,18 +39,26 @@ export interface OnErrorPayload { export type OnErrorFn = (opts: OnErrorPayload) => void +function getPath(event: H3Event): string | null { + if (typeof event.context.params.trpc === 'string') + return event.context.params.trpc + + if (Array.isArray(event.context.params.trpc)) + return event.context.params.trpc.join('/') + + return null +} + export function createNuxtApiHandler({ router, createContext, responseMeta, onError, - url = '/api/trpc', }: { router: TRouter createContext?: CreateContextFn responseMeta?: ResponseMetaFn onError?: OnErrorFn - url?: string }) { return defineEventHandler(async (event) => { const { @@ -58,6 +68,30 @@ export function createNuxtApiHandler({ const $url = createURL(req.url!) + const path = getPath(event) + + if (path === null) { + const error = router.getErrorShape({ + error: new TRPCError({ + message: + 'Param "trpc" not found - is the file named `[trpc]`.ts or `[...trpc].ts`?', + code: 'INTERNAL_SERVER_ERROR', + }), + type: 'unknown', + ctx: undefined, + path: undefined, + input: undefined, + }) + + throw createError({ + statusCode: 500, + statusMessage: JSON.stringify({ + id: -1, + error, + }), + }) + } + const httpResponse = await resolveHTTPResponse({ router, req: { @@ -66,7 +100,7 @@ export function createNuxtApiHandler({ body: isMethod(event, 'GET') ? null : await readBody(event), query: $url.searchParams, }, - path: $url.pathname.substring(url.length + 1), + path, createContext: async () => createContext?.(event), responseMeta, onError: (o) => {