Last active
September 3, 2022 16:08
-
-
Save araqnid/525494f482887eed3ecd312d815bf5b0 to your computer and use it in GitHub Desktop.
Undici request handler for aws-sdk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {HttpHandler, HttpRequest, HttpResponse} from "@aws-sdk/protocol-http"; | |
import {HttpHandlerOptions, RequestHandlerMetadata, RequestHandlerOutput} from "@aws-sdk/types"; | |
import {Agent, Dispatcher} from "undici"; | |
export class UndiciHandler implements HttpHandler { | |
private readonly agent = new Agent() | |
metadata: RequestHandlerMetadata = { | |
handlerProtocol: "http" | |
} | |
async handle(request: HttpRequest, handlerOptions: HttpHandlerOptions = {}): Promise<RequestHandlerOutput<HttpResponse>> { | |
const response = await this.agent.request({ | |
method: request.method as Dispatcher.HttpMethod, | |
headers: request.headers, | |
origin: `${request.protocol}//${request.hostname}`, | |
path: request.path, | |
query: request.query, | |
body: request.body, | |
signal: handlerOptions.abortSignal, | |
}) | |
const headerBag: Record<string, string> = {} | |
for (const [name, value] of Object.entries(response.headers)) { | |
if (typeof value === "string") | |
headerBag[name] = value | |
else if (Array.isArray(value)) | |
headerBag[name] = value[0] | |
} | |
return { | |
response: new HttpResponse({ | |
headers: headerBag, | |
statusCode: response.statusCode, | |
body: response.body | |
}) | |
} | |
} | |
destroy(): void { | |
this.agent.destroy() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment