forked from openapi-ts/openapi-typescript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.d.ts
300 lines (265 loc) · 10 KB
/
index.d.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import type {
ErrorResponse,
FilterKeys,
HttpMethod,
IsOperationRequestBodyOptional,
MediaType,
OperationRequestBodyContent,
PathsWithMethod,
ResponseObjectMap,
RequiredKeysOf,
SuccessResponse,
} from "openapi-typescript-helpers";
/** Options for each client instance */
export interface ClientOptions extends Omit<RequestInit, "headers"> {
/** set the common root URL for all API requests */
baseUrl?: string;
/** custom fetch (defaults to globalThis.fetch) */
fetch?: (input: Request) => Promise<Response>;
/** custom Request (defaults to globalThis.Request) */
Request?: typeof Request;
/** global querySerializer */
querySerializer?: QuerySerializer<unknown> | QuerySerializerOptions;
/** global bodySerializer */
bodySerializer?: BodySerializer<unknown>;
headers?: HeadersOptions;
}
export type HeadersOptions =
| Required<RequestInit>["headers"]
| Record<string, string | number | boolean | (string | number | boolean)[] | null | undefined>;
export type QuerySerializer<T> = (
query: T extends { parameters: any } ? NonNullable<T["parameters"]["query"]> : Record<string, unknown>,
) => string;
/** @see https://swagger.io/docs/specification/serialization/#query */
export type QuerySerializerOptions = {
/** Set serialization for arrays. @see https://swagger.io/docs/specification/serialization/#query */
array?: {
/** default: "form" */
style: "form" | "spaceDelimited" | "pipeDelimited";
/** default: true */
explode: boolean;
};
/** Set serialization for objects. @see https://swagger.io/docs/specification/serialization/#query */
object?: {
/** default: "deepObject" */
style: "form" | "deepObject";
/** default: true */
explode: boolean;
};
/**
* The `allowReserved` keyword specifies whether the reserved characters
* `:/?#[]@!$&'()*+,;=` in parameter values are allowed to be sent as they
* are, or should be percent-encoded. By default, allowReserved is `false`,
* and reserved characters are percent-encoded.
* @see https://swagger.io/docs/specification/serialization/#query
*/
allowReserved?: boolean;
};
export type BodySerializer<T> = (body: OperationRequestBodyContent<T>) => any;
type BodyType<T = unknown> = {
json: T;
text: Awaited<ReturnType<Response["text"]>>;
blob: Awaited<ReturnType<Response["blob"]>>;
arrayBuffer: Awaited<ReturnType<Response["arrayBuffer"]>>;
stream: Response["body"];
};
export type ParseAs = keyof BodyType;
export type ParseAsResponse<T, Options> = Options extends {
parseAs: ParseAs;
}
? BodyType<T>[Options["parseAs"]]
: T;
export interface DefaultParamsOption {
params?: {
query?: Record<string, unknown>;
};
}
export type ParamsOption<T> = T extends {
parameters: any;
}
? RequiredKeysOf<T["parameters"]> extends never
? { params?: T["parameters"] }
: { params: T["parameters"] }
: DefaultParamsOption;
export type RequestBodyOption<T> = OperationRequestBodyContent<T> extends never
? { body?: never }
: IsOperationRequestBodyOptional<T> extends true
? { body?: OperationRequestBodyContent<T> }
: { body: OperationRequestBodyContent<T> };
export type FetchOptions<T> = RequestOptions<T> & Omit<RequestInit, "body" | "headers">;
export type FetchResponse<T, Options, Media extends MediaType> =
| {
data: ParseAsResponse<SuccessResponse<ResponseObjectMap<T>, Media>, Options>;
error?: never;
response: Response;
}
| {
data?: never;
error: ErrorResponse<ResponseObjectMap<T>, Media>;
response: Response;
};
export type RequestOptions<T> = ParamsOption<T> &
RequestBodyOption<T> & {
baseUrl?: string;
querySerializer?: QuerySerializer<T> | QuerySerializerOptions;
bodySerializer?: BodySerializer<T>;
parseAs?: ParseAs;
fetch?: ClientOptions["fetch"];
headers?: HeadersOptions;
};
export type MergedOptions<T = unknown> = {
baseUrl: string;
parseAs: ParseAs;
querySerializer: QuerySerializer<T>;
bodySerializer: BodySerializer<T>;
fetch: typeof globalThis.fetch;
};
export interface MiddlewareCallbackParams {
/** Current Request object */
request: Request;
/** The original OpenAPI schema path (including curly braces) */
readonly schemaPath: string;
/** OpenAPI parameters as provided from openapi-fetch */
readonly params: {
query?: Record<string, unknown>;
header?: Record<string, unknown>;
path?: Record<string, unknown>;
cookie?: Record<string, unknown>;
};
/** Unique ID for this request */
readonly id: string;
/** createClient options (read-only) */
readonly options: MergedOptions;
}
export interface Middleware {
onRequest?: (options: MiddlewareCallbackParams) => void | Request | undefined | Promise<Request | undefined | void>;
onResponse?: (
options: MiddlewareCallbackParams & { response: Response },
) => void | Response | undefined | Promise<Response | undefined | void>;
}
/** This type helper makes the 2nd function param required if params/requestBody are required; otherwise, optional */
export type MaybeOptionalInit<Params, Location extends keyof Params> = RequiredKeysOf<
FetchOptions<FilterKeys<Params, Location>>
> extends never
? FetchOptions<FilterKeys<Params, Location>> | undefined
: FetchOptions<FilterKeys<Params, Location>>;
// The final init param to accept.
// - Determines if the param is optional or not.
// - Performs arbitrary [key: string] addition.
// Note: the addition MUST happen after all the inference happens (otherwise TS can’t infer if init is required or not).
type InitParam<Init> = RequiredKeysOf<Init> extends never
? [(Init & { [key: string]: unknown })?]
: [Init & { [key: string]: unknown }];
export type ClientMethod<
Paths extends Record<string, Record<HttpMethod, {}>>,
Method extends HttpMethod,
Media extends MediaType,
> = <Path extends PathsWithMethod<Paths, Method>, Init extends MaybeOptionalInit<Paths[Path], Method>>(
url: Path,
...init: InitParam<Init>
) => Promise<FetchResponse<Paths[Path][Method], Init, Media>>;
export type ClientForPath<PathInfo, Media extends MediaType> = {
[Method in keyof PathInfo as Uppercase<string & Method>]: <Init extends MaybeOptionalInit<PathInfo, Method>>(
...init: InitParam<Init>
) => Promise<FetchResponse<PathInfo[Method], Init, Media>>;
};
export interface Client<Paths extends {}, Media extends MediaType = MediaType> {
/** Call a GET endpoint */
GET: ClientMethod<Paths, "get", Media>;
/** Call a PUT endpoint */
PUT: ClientMethod<Paths, "put", Media>;
/** Call a POST endpoint */
POST: ClientMethod<Paths, "post", Media>;
/** Call a DELETE endpoint */
DELETE: ClientMethod<Paths, "delete", Media>;
/** Call a OPTIONS endpoint */
OPTIONS: ClientMethod<Paths, "options", Media>;
/** Call a HEAD endpoint */
HEAD: ClientMethod<Paths, "head", Media>;
/** Call a PATCH endpoint */
PATCH: ClientMethod<Paths, "patch", Media>;
/** Call a TRACE endpoint */
TRACE: ClientMethod<Paths, "trace", Media>;
/** Register middleware */
use(...middleware: Middleware[]): void;
/** Unregister middleware */
eject(...middleware: Middleware[]): void;
}
export type ClientPathsWithMethod<
CreatedClient extends Client<any, any>,
Method extends HttpMethod,
> = CreatedClient extends Client<infer Paths, infer _Media> ? PathsWithMethod<Paths, Method> : never;
export type MethodResponse<
CreatedClient extends Client<any, any>,
Method extends HttpMethod,
Path extends ClientPathsWithMethod<CreatedClient, Method>,
Options = {},
> = CreatedClient extends Client<infer Paths extends { [key: string]: any }, infer Media extends MediaType>
? NonNullable<FetchResponse<Paths[Path][Method], Options, Media>["data"]>
: never;
export default function createClient<Paths extends {}, Media extends MediaType = MediaType>(
clientOptions?: ClientOptions,
): Client<Paths, Media>;
export type PathBasedClient<Paths, Media extends MediaType = MediaType> = {
[Path in keyof Paths]: ClientForPath<Paths[Path], Media>;
};
export declare function wrapAsPathBasedClient<Paths extends {}, Media extends MediaType = MediaType>(
client: Client<Paths, Media>,
): PathBasedClient<Paths, Media>;
export declare function createPathBasedClient<Paths extends {}, Media extends MediaType = MediaType>(
clientOptions?: ClientOptions,
): PathBasedClient<Paths, Media>;
/** Serialize primitive params to string */
export declare function serializePrimitiveParam(
name: string,
value: string,
options?: { allowReserved?: boolean },
): string;
/** Serialize object param to string */
export declare function serializeObjectParam(
name: string,
value: Record<string, unknown>,
options: {
style: "simple" | "label" | "matrix" | "form" | "deepObject";
explode: boolean;
allowReserved?: boolean;
},
): string;
/** Serialize array param to string */
export declare function serializeArrayParam(
name: string,
value: unknown[],
options: {
style: "simple" | "label" | "matrix" | "form" | "spaceDelimited" | "pipeDelimited";
explode: boolean;
allowReserved?: boolean;
},
): string;
/** Serialize query params to string */
export declare function createQuerySerializer<T = unknown>(
options?: QuerySerializerOptions,
): (queryParams: T) => string;
/**
* Handle different OpenAPI 3.x serialization styles
* @type {import("./index.js").defaultPathSerializer}
* @see https://swagger.io/docs/specification/serialization/#path
*/
export declare function defaultPathSerializer(pathname: string, pathParams: Record<string, unknown>): string;
/** Serialize body object to string */
export declare function defaultBodySerializer<T>(body: T): string;
/** Construct URL string from baseUrl and handle path and query params */
export declare function createFinalURL<O>(
pathname: string,
options: {
baseUrl: string;
params: {
query?: Record<string, unknown>;
path?: Record<string, unknown>;
};
querySerializer: QuerySerializer<O>;
},
): string;
/** Merge headers a and b, with b taking priority */
export declare function mergeHeaders(...allHeaders: (HeadersOptions | undefined)[]): Headers;
/** Remove trailing slash from url */
export declare function removeTrailingSlash(url: string): string;