-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
httpUtils.ts
187 lines (167 loc) · 4.4 KB
/
httpUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import { ProcedureType } from '@trpc/server';
import { TRPCResponse } from '@trpc/server/rpc';
import { getFetch } from '../../getFetch';
import { getAbortController } from '../../internals/getAbortController';
import {
AbortControllerEsque,
FetchEsque,
RequestInitEsque,
ResponseEsque,
} from '../../internals/types';
import { HTTPHeaders, PromiseAndCancel, TRPCClientRuntime } from '../types';
/**
* @internal
*/
export interface HTTPLinkBaseOptions {
url: string;
/**
* Add ponyfill for fetch
*/
fetch?: FetchEsque;
/**
* Add ponyfill for AbortController
*/
AbortController?: AbortControllerEsque | null;
}
export interface ResolvedHTTPLinkOptions {
url: string;
fetch: FetchEsque;
AbortController: AbortControllerEsque | null;
}
export function resolveHTTPLinkOptions(
opts: HTTPLinkBaseOptions,
): ResolvedHTTPLinkOptions {
return {
url: opts.url,
fetch: getFetch(opts.fetch),
AbortController: getAbortController(opts.AbortController),
};
}
// https://github.com/trpc/trpc/pull/669
function arrayToDict(array: unknown[]) {
const dict: Record<number, unknown> = {};
for (let index = 0; index < array.length; index++) {
const element = array[index];
dict[index] = element;
}
return dict;
}
const METHOD = {
query: 'GET',
mutation: 'POST',
} as const;
export interface HTTPResult {
json: TRPCResponse;
meta: {
response: ResponseEsque;
};
}
type GetInputOptions = {
runtime: TRPCClientRuntime;
} & ({ inputs: unknown[] } | { input: unknown });
function getInput(opts: GetInputOptions) {
return 'input' in opts
? opts.runtime.transformer.serialize(opts.input)
: arrayToDict(
opts.inputs.map((_input) => opts.runtime.transformer.serialize(_input)),
);
}
export type HTTPBaseRequestOptions = ResolvedHTTPLinkOptions &
GetInputOptions & {
type: ProcedureType;
path: string;
};
export type GetUrl = (opts: HTTPBaseRequestOptions) => string;
export type GetBody = (
opts: HTTPBaseRequestOptions,
) => RequestInitEsque['body'];
export type ContentOptions = {
contentTypeHeader?: string;
getUrl: GetUrl;
getBody: GetBody;
};
export const getUrl: GetUrl = (opts) => {
let url = opts.url + '/' + opts.path;
const queryParts: string[] = [];
if ('inputs' in opts) {
queryParts.push('batch=1');
}
if (opts.type === 'query') {
const input = getInput(opts);
if (input !== undefined) {
queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);
}
}
if (queryParts.length) {
url += '?' + queryParts.join('&');
}
return url;
};
export const getBody: GetBody = (opts) => {
if (opts.type === 'query') {
return undefined;
}
const input = getInput(opts);
return input !== undefined ? JSON.stringify(input) : undefined;
};
export type Requester = (
opts: HTTPBaseRequestOptions & {
headers: () => HTTPHeaders | Promise<HTTPHeaders>;
},
) => PromiseAndCancel<HTTPResult>;
export const jsonHttpRequester: Requester = (opts) => {
return httpRequest({
...opts,
contentTypeHeader: 'application/json',
getUrl,
getBody,
});
};
export type HTTPRequestOptions = HTTPBaseRequestOptions &
ContentOptions & {
headers: () => HTTPHeaders | Promise<HTTPHeaders>;
};
export function httpRequest(
opts: HTTPRequestOptions,
): PromiseAndCancel<HTTPResult> {
const { type } = opts;
const ac = opts.AbortController ? new opts.AbortController() : null;
const promise = new Promise<HTTPResult>((resolve, reject) => {
const url = opts.getUrl(opts);
const body = opts.getBody(opts);
const meta = {} as HTTPResult['meta'];
Promise.resolve(opts.headers())
.then((headers) => {
/* istanbul ignore if -- @preserve */
if (type === 'subscription') {
throw new Error('Subscriptions should use wsLink');
}
return opts.fetch(url, {
method: METHOD[type],
signal: ac?.signal,
body: body,
headers: {
...(opts.contentTypeHeader
? { 'content-type': opts.contentTypeHeader }
: {}),
...headers,
},
});
})
.then((_res) => {
meta.response = _res;
return _res.json();
})
.then((json) => {
resolve({
json: json as TRPCResponse,
meta,
});
})
.catch(reject);
});
const cancel = () => {
ac?.abort();
};
return { promise, cancel };
}