MCPcopy
hub / github.com/blitz-js/blitz / rpcAppHandler

Function rpcAppHandler

packages/blitz-rpc/src/index-server.ts:365–488  ·  view source on GitHub ↗
(config?: RpcConfig)

Source from the content-addressed store, hash-verified

363type Params = Record<string, unknown>
364
365export function rpcAppHandler(config?: RpcConfig) {
366 registerBlitzErrorClasses()
367 async function handleRpcRequest(req: Request, segmentData: {params: Promise<Params>}, ctx?: Ctx) {
368 const params = await segmentData.params
369 const session = ctx?.session
370 const resolverMap = await getResolverMap()
371 assert(resolverMap, "No query or mutation resolvers found")
372
373 assert(
374 Array.isArray(params.blitz),
375 "It seems your Blitz RPC endpoint file is not named [[...blitz]].(jt)s. Please ensure it is",
376 )
377
378 const relativeRoutePath = (params.blitz as string[])?.join("/")
379 const routePath = "/" + relativeRoutePath
380 const resolverName = routePath.replace(/(\/api\/rpc)?\//, "")
381 const rpcLogger = new RpcLogger(resolverName, config?.logging)
382
383 const loadableResolver = resolverMap?.[routePath]?.resolver
384 if (!loadableResolver) {
385 throw new Error("No resolver for path: " + routePath)
386 }
387
388 const {default: resolver, config: resolverConfig} = await loadableResolver()
389
390 if (!resolver) {
391 throw new Error("No default export for resolver path: " + routePath)
392 }
393
394 const resolverConfigWithDefaults = {...defaultConfig, ...resolverConfig}
395
396 if (req.method === "HEAD") {
397 // We used to initiate database connection here
398 return new Response(null, {status: 200})
399 }
400
401 if (
402 req.method === "POST" ||
403 (req.method === "GET" && resolverConfigWithDefaults.httpMethod === "GET")
404 ) {
405 const body = await req.json()
406 if (req.method === "POST" && typeof body.params === "undefined") {
407 const error = {message: "Request body is missing the `params` key"}
408 rpcLogger.error(error.message)
409 return new Response(JSON.stringify({result: null, error}), {status: 400})
410 }
411
412 try {
413 const data = deserialize({
414 json:
415 req.method === "POST"
416 ? body.params
417 : params.params
418 ? parse(`${params.params}`)
419 : undefined,
420 meta:
421 req.method === "POST"
422 ? body.meta?.params

Callers 3

route.tsFile · 0.90
route.tsFile · 0.90
route.tsFile · 0.90

Calls 1

Tested by

no test coverage detected