UNPKG

1.83 kBPlain TextView Raw
1// Copyright (c) .NET Foundation. All rights reserved.
2// Licensed under the MIT License.
3
4import * as types from '@azure/functions';
5import { HttpResponseInit } from '@azure/functions';
6import { Blob } from 'buffer';
7import { ReadableStream } from 'stream/web';
8import { FormData, Headers, Response as uResponse, ResponseInit as uResponseInit } from 'undici';
9import { isDefined } from '../utils/nonNull';
10
11export class HttpResponse implements types.HttpResponse {
12 readonly cookies: types.Cookie[];
13 readonly enableContentNegotiation: boolean;
14
15 #uRes: uResponse;
16
17 constructor(resInit?: HttpResponseInit) {
18 const uResInit: uResponseInit = { status: resInit?.status, headers: resInit?.headers };
19 if (isDefined(resInit?.jsonBody)) {
20 this.#uRes = uResponse.json(resInit?.jsonBody, uResInit);
21 } else {
22 this.#uRes = new uResponse(resInit?.body, uResInit);
23 }
24
25 this.cookies = resInit?.cookies || [];
26 this.enableContentNegotiation = !!resInit?.enableContentNegotiation;
27 }
28
29 get status(): number {
30 return this.#uRes.status;
31 }
32
33 get headers(): Headers {
34 return this.#uRes.headers;
35 }
36
37 get body(): ReadableStream<any> | null {
38 return this.#uRes.body;
39 }
40
41 get bodyUsed(): boolean {
42 return this.#uRes.bodyUsed;
43 }
44
45 async arrayBuffer(): Promise<ArrayBuffer> {
46 return this.#uRes.arrayBuffer();
47 }
48
49 async blob(): Promise<Blob> {
50 return this.#uRes.blob();
51 }
52
53 async formData(): Promise<FormData> {
54 return this.#uRes.formData();
55 }
56
57 async json(): Promise<unknown> {
58 return this.#uRes.json();
59 }
60
61 async text(): Promise<string> {
62 return this.#uRes.text();
63 }
64}