Skip to content

Commit

Permalink
feat: add $HAAL-returnBody special return
Browse files Browse the repository at this point in the history
  • Loading branch information
NamesMT committed Jul 19, 2024
1 parent fbb8b40 commit 6cd75e6
Showing 1 changed file with 36 additions and 5 deletions.
41 changes: 36 additions & 5 deletions src/handler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import crypto from 'node:crypto'
import type { ReadableStreamDefaultReader } from 'node:stream/web'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import type { Env, Hono, Schema } from 'hono'
import type { LambdaEvent } from '@namesmt/utils-lambda'

import type { APIGatewayProxyStructuredResultV2 } from 'aws-lambda'
import type { LambdaContext, LambdaHandler, LambdaHandlerResult } from './types'

import { getProcessor } from './common'
Expand All @@ -19,6 +22,19 @@ async function writableWriteReadable(writer: NodeJS.WritableStream, reader: Read
writer.end()
}

function stringToReadable(str: string): Readable {
// eslint-disable-next-line node/prefer-global/buffer
return Readable.from(Buffer.from(str))
}

function resultToStreamMetadata(result: APIGatewayProxyStructuredResultV2) {
return {
statusCode: result.statusCode,
headers: result.headers,
cookies: result.cookies,
}
}

function responseToStreamMetadata(res: Response) {
const headers: Record<string, string> = {}
const cookies: string[] = []
Expand Down Expand Up @@ -54,14 +70,26 @@ export function streamHandle<
context,
})

// Update response stream metadata
responseStream = awslambda.HttpResponseStream.from(responseStream, responseToStreamMetadata(res))
if (res.headers.get('$HAAL-returnBody')) {
const result = (await res.json()) as APIGatewayProxyStructuredResultV2

// Update response stream metadata
responseStream = awslambda.HttpResponseStream.from(responseStream, resultToStreamMetadata(result))

const bodyStream = stringToReadable(result.body || '')

if (res.body) {
await writableWriteReadable(responseStream, res.body.getReader())
await pipeline(bodyStream, responseStream)
}
else {
responseStream.write('')
// Update response stream metadata
responseStream = awslambda.HttpResponseStream.from(responseStream, responseToStreamMetadata(res))

if (res.body) {
await writableWriteReadable(responseStream, res.body.getReader())
}
else {
responseStream.write('')
}
}
}
catch (error) {
Expand Down Expand Up @@ -89,6 +117,9 @@ export function handle<E extends Env = Env, S extends Schema = {}, BasePath exte
lambdaContext,
})

if (res.headers.get('$HAAL-returnBody'))
return (await res.json()) as LambdaHandlerResult

return processor.createResult(event, res)
}
}

0 comments on commit 6cd75e6

Please sign in to comment.