1 |
|
2 |
|
3 |
|
4 | import * as types from '@azure/functions';
|
5 | import { HttpRequestParams, HttpRequestUser } from '@azure/functions';
|
6 | import { RpcHttpData } from '@azure/functions-core';
|
7 | import { Blob } from 'buffer';
|
8 | import { ReadableStream } from 'stream/web';
|
9 | import { FormData, Headers, Request as uRequest } from 'undici';
|
10 | import { URLSearchParams } from 'url';
|
11 | import { fromNullableMapping } from '../converters/fromRpcNullable';
|
12 | import { nonNullProp } from '../utils/nonNull';
|
13 | import { extractHttpUserFromHeaders } from './extractHttpUserFromHeaders';
|
14 |
|
15 | export class HttpRequest implements types.HttpRequest {
|
16 | readonly query: URLSearchParams;
|
17 | readonly params: HttpRequestParams;
|
18 |
|
19 | #cachedUser?: HttpRequestUser | null;
|
20 | #uReq: uRequest;
|
21 | #body?: Buffer | string;
|
22 |
|
23 | constructor(rpcHttp: RpcHttpData) {
|
24 | const url = nonNullProp(rpcHttp, 'url');
|
25 |
|
26 | if (rpcHttp.body?.bytes) {
|
27 | this.#body = Buffer.from(rpcHttp.body?.bytes);
|
28 | } else if (rpcHttp.body?.string) {
|
29 | this.#body = rpcHttp.body.string;
|
30 | }
|
31 |
|
32 | this.#uReq = new uRequest(url, {
|
33 | body: this.#body,
|
34 | method: nonNullProp(rpcHttp, 'method'),
|
35 | headers: fromNullableMapping(rpcHttp.nullableHeaders, rpcHttp.headers),
|
36 | });
|
37 |
|
38 | this.query = new URLSearchParams(fromNullableMapping(rpcHttp.nullableQuery, rpcHttp.query));
|
39 | this.params = fromNullableMapping(rpcHttp.nullableParams, rpcHttp.params);
|
40 | }
|
41 |
|
42 | get url(): string {
|
43 | return this.#uReq.url;
|
44 | }
|
45 |
|
46 | get method(): string {
|
47 | return this.#uReq.method;
|
48 | }
|
49 |
|
50 | get headers(): Headers {
|
51 | return this.#uReq.headers;
|
52 | }
|
53 |
|
54 | get user(): HttpRequestUser | null {
|
55 | if (this.#cachedUser === undefined) {
|
56 | this.#cachedUser = extractHttpUserFromHeaders(this.headers);
|
57 | }
|
58 |
|
59 | return this.#cachedUser;
|
60 | }
|
61 |
|
62 | get body(): ReadableStream<any> | null {
|
63 | return this.#uReq.body;
|
64 | }
|
65 |
|
66 | get bodyUsed(): boolean {
|
67 | return this.#uReq.bodyUsed;
|
68 | }
|
69 |
|
70 | async arrayBuffer(): Promise<ArrayBuffer> {
|
71 | return this.#uReq.arrayBuffer();
|
72 | }
|
73 |
|
74 | async blob(): Promise<Blob> {
|
75 | return this.#uReq.blob();
|
76 | }
|
77 |
|
78 | async formData(): Promise<FormData> {
|
79 | return this.#uReq.formData();
|
80 | }
|
81 |
|
82 | async json(): Promise<unknown> {
|
83 | return this.#uReq.json();
|
84 | }
|
85 |
|
86 | async text(): Promise<string> {
|
87 | return this.#uReq.text();
|
88 | }
|
89 | }
|