Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 32 additions & 49 deletions client/client/client.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,7 @@
import { createSseClient } from '../core/serverSentEvents.gen';
import type { HttpMethod } from '../core/types.gen';
import { getValidRequestBody } from '../core/utils.gen';
import type {
Client,
Config,
RequestOptions,
ResolvedRequestOptions,
} from './types.gen';
import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen';
import {
buildUrl,
createConfig,
Expand All @@ -34,12 +29,7 @@ export const createClient = (config: Config = {}): Client => {
return getConfig();
};

const interceptors = createInterceptors<
Request,
Response,
unknown,
ResolvedRequestOptions
>();
const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>();

const beforeRequest = async (options: RequestOptions) => {
const opts = {
Expand Down Expand Up @@ -105,12 +95,7 @@ export const createClient = (config: Config = {}): Client => {

for (const fn of interceptors.error.fns) {
if (fn) {
finalError = (await fn(
error,
undefined as any,
request,
opts,
)) as unknown;
finalError = (await fn(error, undefined as any, request, opts)) as unknown;
}
}

Expand Down Expand Up @@ -147,10 +132,7 @@ export const createClient = (config: Config = {}): Client => {
? getParseAs(response.headers.get('Content-Type'))
: opts.parseAs) ?? 'json';

if (
response.status === 204 ||
response.headers.get('Content-Length') === '0'
) {
if (response.status === 204 || response.headers.get('Content-Length') === '0') {
let emptyData: any;
switch (parseAs) {
case 'arrayBuffer':
Expand Down Expand Up @@ -182,10 +164,16 @@ export const createClient = (config: Config = {}): Client => {
case 'arrayBuffer':
case 'blob':
case 'formData':
case 'json':
case 'text':
data = await response[parseAs]();
break;
case 'json': {
// Some servers return 200 with no Content-Length and empty body.
// response.json() would throw; read as text and parse if non-empty.
const text = await response.text();
data = text ? JSON.parse(text) : {};
break;
}
case 'stream':
return opts.responseStyle === 'data'
? response.body
Expand Down Expand Up @@ -246,34 +234,29 @@ export const createClient = (config: Config = {}): Client => {
};
};

const makeMethodFn =
(method: Uppercase<HttpMethod>) => (options: RequestOptions) =>
request({ ...options, method });
const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>
request({ ...options, method });

const makeSseFn =
(method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
const { opts, url } = await beforeRequest(options);
return createSseClient({
...opts,
body: opts.body as BodyInit | null | undefined,
headers: opts.headers as unknown as Record<string, string>,
method,
onRequest: async (url, init) => {
let request = new Request(url, init);
for (const fn of interceptors.request.fns) {
if (fn) {
request = await fn(request, opts);
}
const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
const { opts, url } = await beforeRequest(options);
return createSseClient({
...opts,
body: opts.body as BodyInit | null | undefined,
headers: opts.headers as unknown as Record<string, string>,
method,
onRequest: async (url, init) => {
let request = new Request(url, init);
for (const fn of interceptors.request.fns) {
if (fn) {
request = await fn(request, opts);
}
return request;
},
serializedBody: getValidRequestBody(opts) as
| BodyInit
| null
| undefined,
url,
});
};
}
return request;
},
serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,
url,
});
};

return {
buildUrl,
Expand Down
52 changes: 12 additions & 40 deletions client/client/types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,13 @@ import type {
ServerSentEventsOptions,
ServerSentEventsResult,
} from '../core/serverSentEvents.gen';
import type {
Client as CoreClient,
Config as CoreConfig,
} from '../core/types.gen';
import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen';
import type { Middleware } from './utils.gen';

export type ResponseStyle = 'data' | 'fields';

export interface Config<T extends ClientOptions = ClientOptions>
extends Omit<RequestInit, 'body' | 'headers' | 'method'>,
CoreConfig {
extends Omit<RequestInit, 'body' | 'headers' | 'method'>, CoreConfig {
/**
* Base URL for all requests made by this client.
*/
Expand All @@ -42,14 +38,7 @@ export interface Config<T extends ClientOptions = ClientOptions>
*
* @default 'auto'
*/
parseAs?:
| 'arrayBuffer'
| 'auto'
| 'blob'
| 'formData'
| 'json'
| 'stream'
| 'text';
parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text';
/**
* Should we return only data or multiple fields (data, error, response, etc.)?
*
Expand All @@ -69,7 +58,9 @@ export interface RequestOptions<
TResponseStyle extends ResponseStyle = 'fields',
ThrowOnError extends boolean = boolean,
Url extends string = string,
> extends Config<{
>
extends
Config<{
responseStyle: TResponseStyle;
throwOnError: ThrowOnError;
}>,
Expand Down Expand Up @@ -116,32 +107,22 @@ export type RequestResult<
? TData[keyof TData]
: TData
: {
data: TData extends Record<string, unknown>
? TData[keyof TData]
: TData;
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
request: Request;
response: Response;
}
>
: Promise<
TResponseStyle extends 'data'
?
| (TData extends Record<string, unknown>
? TData[keyof TData]
: TData)
| undefined
? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined
: (
| {
data: TData extends Record<string, unknown>
? TData[keyof TData]
: TData;
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
error: undefined;
}
| {
data: undefined;
error: TError extends Record<string, unknown>
? TError[keyof TError]
: TError;
error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
}
) & {
request: Request;
Expand Down Expand Up @@ -180,10 +161,7 @@ type RequestFn = <
TResponseStyle extends ResponseStyle = 'fields',
>(
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'> &
Pick<
Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>,
'method'
>,
Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, 'method'>,
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;

type BuildUrlFn = <
Expand All @@ -197,13 +175,7 @@ type BuildUrlFn = <
options: TData & Options<TData>,
) => string;

export type Client = CoreClient<
RequestFn,
Config,
MethodFn,
BuildUrlFn,
SseFn
> & {
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>;
};

Expand Down
28 changes: 6 additions & 22 deletions client/client/utils.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,7 @@ export const createQuerySerializer = <T = unknown>({
/**
* Infers parseAs value from provided Content-Type header.
*/
export const getParseAs = (
contentType: string | null,
): Exclude<Config['parseAs'], 'auto'> => {
export const getParseAs = (contentType: string | null): Exclude<Config['parseAs'], 'auto'> => {
if (!contentType) {
// If no Content-Type header is provided, the best we can do is return the raw response body,
// which is effectively the same as the 'stream' option.
Expand All @@ -80,10 +78,7 @@ export const getParseAs = (
return;
}

if (
cleanContent.startsWith('application/json') ||
cleanContent.endsWith('+json')
) {
if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {
return 'json';
}

Expand All @@ -92,9 +87,7 @@ export const getParseAs = (
}

if (
['application/', 'audio/', 'image/', 'video/'].some((type) =>
cleanContent.startsWith(type),
)
['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))
) {
return 'blob';
}
Expand Down Expand Up @@ -201,10 +194,7 @@ export const mergeHeaders = (
continue;
}

const iterator =
header instanceof Headers
? headersEntries(header)
: Object.entries(header);
const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);

for (const [key, value] of iterator) {
if (value === null) {
Expand Down Expand Up @@ -233,10 +223,7 @@ type ErrInterceptor<Err, Res, Req, Options> = (
options: Options,
) => Err | Promise<Err>;

type ReqInterceptor<Req, Options> = (
request: Req,
options: Options,
) => Req | Promise<Req>;
type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;

type ResInterceptor<Res, Req, Options> = (
response: Res,
Expand Down Expand Up @@ -270,10 +257,7 @@ class Interceptors<Interceptor> {
return this.fns.indexOf(id);
}

update(
id: number | Interceptor,
fn: Interceptor,
): number | Interceptor | false {
update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {
const index = this.getInterceptorIndex(id);
if (this.fns[index]) {
this.fns[index] = fn;
Expand Down
3 changes: 1 addition & 2 deletions client/core/auth.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ export const getAuthToken = async (
auth: Auth,
callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
): Promise<string | undefined> => {
const token =
typeof callback === 'function' ? await callback(auth) : callback;
const token = typeof callback === 'function' ? await callback(auth) : callback;

if (!token) {
return;
Expand Down
26 changes: 5 additions & 21 deletions client/core/bodySerializer.gen.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
// This file is auto-generated by @hey-api/openapi-ts

import type {
ArrayStyle,
ObjectStyle,
SerializerOptions,
} from './pathSerializer.gen';
import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen';

export type QuerySerializer = (query: Record<string, unknown>) => string;

Expand All @@ -24,11 +20,7 @@ export type QuerySerializerOptions = QuerySerializerOptionsObject & {
parameters?: Record<string, QuerySerializerOptionsObject>;
};

const serializeFormDataPair = (
data: FormData,
key: string,
value: unknown,
): void => {
const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {
if (typeof value === 'string' || value instanceof Blob) {
data.append(key, value);
} else if (value instanceof Date) {
Expand All @@ -38,11 +30,7 @@ const serializeFormDataPair = (
}
};

const serializeUrlSearchParamsPair = (
data: URLSearchParams,
key: string,
value: unknown,
): void => {
const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => {
if (typeof value === 'string') {
data.append(key, value);
} else {
Expand Down Expand Up @@ -73,15 +61,11 @@ export const formDataBodySerializer = {

export const jsonBodySerializer = {
bodySerializer: <T>(body: T): string =>
JSON.stringify(body, (_key, value) =>
typeof value === 'bigint' ? value.toString() : value,
),
JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)),
};

export const urlSearchParamsBodySerializer = {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
body: T,
): string => {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T): string => {
const data = new URLSearchParams();

Object.entries(body).forEach(([key, value]) => {
Expand Down
Loading
Loading