Skip to content

Commit

Permalink
Merge pull request #7 from michealroberts/refactor/defineNitroTRPCEve…
Browse files Browse the repository at this point in the history
…ntHandler

refactor: Amend to setHeader & setResponseStatus h3 methods in defineNitroEventHandler.
  • Loading branch information
michealroberts authored Jun 8, 2023
2 parents 6f7fc4f + 05556e6 commit 80c8196
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/defineNitroTRPCEventHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,15 @@ import { type HTTPRequest, type ResponseMeta, resolveHTTPResponse } from '@trpc/

import { createURL } from 'ufo'

import { type EventHandler, type H3Event, defineEventHandler, readBody, isMethod } from 'h3'
import {
type EventHandler,
type H3Event,
defineEventHandler,
readBody,
setHeader,
isMethod,
setResponseStatus
} from 'h3'

/*****************************************************************************************************************/

Expand Down Expand Up @@ -92,7 +100,7 @@ export const defineNitroTRPCEventHandler: NitroRequestHandler = <TRouter extends
}) => {
return defineEventHandler(async event => {
// Extract the request and response objects from the H3 event:
const { req: request, res: response } = event.node
const { req: request } = event.node

// Create a URL object from the request URL:
const url = createURL(request.url!)
Expand Down Expand Up @@ -127,12 +135,14 @@ export const defineNitroTRPCEventHandler: NitroRequestHandler = <TRouter extends
})

// Set the statis code accordingly:
response.statusCode = status
setResponseStatus(event, status)

// Merge response headers accordingly:
headers &&
Object.keys(headers).forEach(key => {
response.setHeader(key, headers[key]!)
if (headers[key]) {
setHeader(event, key, headers[key]!)
}
})

// Return the response body "as is", JSON "stringified":
Expand Down

0 comments on commit 80c8196

Please sign in to comment.