Skip to content

Instantly share code, notes, and snippets.

@araqnid
Last active September 3, 2022 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save araqnid/525494f482887eed3ecd312d815bf5b0 to your computer and use it in GitHub Desktop.
Save araqnid/525494f482887eed3ecd312d815bf5b0 to your computer and use it in GitHub Desktop.
Undici request handler for aws-sdk
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