Skip to content

Commit 48c7fa3

Browse files
committed
fix(sdk): handle conflicts between method names and subclasses in class-based SDKs
1 parent 7e1a276 commit 48c7fa3

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+46341
-87
lines changed

.changeset/petite-walls-behave.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@hey-api/openapi-ts': patch
3+
---
4+
5+
fix(sdk): handle conflicts between method names and subclasses in class-based SDKs

dev/openapi-ts.config.ts

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/* eslint-disable @typescript-eslint/no-unused-vars */
2+
// @ts-ignore
23
import path from 'node:path';
34

45
// @ts-ignore
@@ -8,6 +9,7 @@ import { defineConfig, utils } from '@hey-api/openapi-ts';
89

910
// @ts-ignore
1011
import { myClientPlugin } from '../packages/openapi-ts-tests/main/test/custom/client/plugin';
12+
// @ts-ignore
1113
import { getSpecsPath } from '../packages/openapi-ts-tests/utils';
1214

1315
// @ts-ignore
@@ -32,26 +34,26 @@ export default defineConfig(() => {
3234
// openapi: '3.1.0',
3335
// paths: {},
3436
// },
35-
path: 'https://gist.githubusercontent.com/nghiepdev/b2c9996750505ec82adb04fdc9b95ea6/raw/ebe990458001a5c4d3e1de0218f93dcb8f132db8/test-openapi.json',
36-
// path: path.resolve(
37-
// getSpecsPath(),
38-
// // '3.0.x',
39-
// '3.1.x',
40-
// // 'circular.yaml',
41-
// // 'dutchie.json',
42-
// // 'invalid',
43-
// // 'openai.yaml',
44-
// // 'full.yaml',
45-
// // 'opencode.yaml',
46-
// // 'sdk-instance.yaml',
47-
// // 'string-with-format.yaml',
48-
// // 'transformers.json',
49-
// // 'type-format.yaml',
50-
// 'validators.yaml',
51-
// // 'validators-circular-ref.json',
52-
// // 'validators-circular-ref-2.yaml',
53-
// // 'zoom-video-sdk.json',
54-
// ),
37+
path: path.resolve(
38+
getSpecsPath(),
39+
'3.0.x',
40+
// '3.1.x',
41+
// 'circular.yaml',
42+
// 'dutchie.json',
43+
// 'invalid',
44+
// 'openai.yaml',
45+
// 'full.yaml',
46+
// 'opencode.yaml',
47+
'sdk-circular-bug.yaml',
48+
// 'sdk-instance.yaml',
49+
// 'string-with-format.yaml',
50+
// 'transformers.json',
51+
// 'type-format.yaml',
52+
// 'validators.yaml',
53+
// 'validators-circular-ref.json',
54+
// 'validators-circular-ref-2.yaml',
55+
// 'zoom-video-sdk.json',
56+
),
5557
// path: 'https://get.heyapi.dev/hey-api/backend?branch=main&version=1.0.0',
5658
// path: 'http://localhost:4000/',
5759
// path: 'http://localhost:8000/openapi.json',
@@ -249,7 +251,7 @@ export default defineConfig(() => {
249251
// },
250252
},
251253
{
252-
// asClass: true,
254+
asClass: true,
253255
// auth: false,
254256
// classNameBuilder: '{{name}}',
255257
// classNameBuilder: '{{name}}Service',
@@ -260,7 +262,7 @@ export default defineConfig(() => {
260262
// fields.unwrap('path')
261263
// },
262264
// include...
263-
// instance: true,
265+
instance: true,
264266
name: '@hey-api/sdk',
265267
// operationId: false,
266268
// paramsStructure: 'flat',
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// This file is auto-generated by @hey-api/openapi-ts
2+
3+
import { type ClientOptions, type Config, createClient, createConfig } from './client';
4+
import type { ClientOptions as ClientOptions2 } from './types.gen';
5+
6+
/**
7+
* The `createClientConfig()` function will be called on client initialization
8+
* and the returned object will become the client's initial configuration.
9+
*
10+
* You may want to initialize your client this way instead of calling
11+
* `setConfig()`. This is useful for example if you're using Next.js
12+
* to ensure your client always has the correct values.
13+
*/
14+
export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
15+
16+
export const client = createClient(createConfig<ClientOptions2>());
Lines changed: 268 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,268 @@
1+
// This file is auto-generated by @hey-api/openapi-ts
2+
3+
import { createSseClient } from '../core/serverSentEvents.gen';
4+
import type { HttpMethod } from '../core/types.gen';
5+
import { getValidRequestBody } from '../core/utils.gen';
6+
import type {
7+
Client,
8+
Config,
9+
RequestOptions,
10+
ResolvedRequestOptions,
11+
} from './types.gen';
12+
import {
13+
buildUrl,
14+
createConfig,
15+
createInterceptors,
16+
getParseAs,
17+
mergeConfigs,
18+
mergeHeaders,
19+
setAuthParams,
20+
} from './utils.gen';
21+
22+
type ReqInit = Omit<RequestInit, 'body' | 'headers'> & {
23+
body?: any;
24+
headers: ReturnType<typeof mergeHeaders>;
25+
};
26+
27+
export const createClient = (config: Config = {}): Client => {
28+
let _config = mergeConfigs(createConfig(), config);
29+
30+
const getConfig = (): Config => ({ ..._config });
31+
32+
const setConfig = (config: Config): Config => {
33+
_config = mergeConfigs(_config, config);
34+
return getConfig();
35+
};
36+
37+
const interceptors = createInterceptors<
38+
Request,
39+
Response,
40+
unknown,
41+
ResolvedRequestOptions
42+
>();
43+
44+
const beforeRequest = async (options: RequestOptions) => {
45+
const opts = {
46+
..._config,
47+
...options,
48+
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
49+
headers: mergeHeaders(_config.headers, options.headers),
50+
serializedBody: undefined,
51+
};
52+
53+
if (opts.security) {
54+
await setAuthParams({
55+
...opts,
56+
security: opts.security,
57+
});
58+
}
59+
60+
if (opts.requestValidator) {
61+
await opts.requestValidator(opts);
62+
}
63+
64+
if (opts.body !== undefined && opts.bodySerializer) {
65+
opts.serializedBody = opts.bodySerializer(opts.body);
66+
}
67+
68+
// remove Content-Type header if body is empty to avoid sending invalid requests
69+
if (opts.body === undefined || opts.serializedBody === '') {
70+
opts.headers.delete('Content-Type');
71+
}
72+
73+
const url = buildUrl(opts);
74+
75+
return { opts, url };
76+
};
77+
78+
const request: Client['request'] = async (options) => {
79+
// @ts-expect-error
80+
const { opts, url } = await beforeRequest(options);
81+
const requestInit: ReqInit = {
82+
redirect: 'follow',
83+
...opts,
84+
body: getValidRequestBody(opts),
85+
};
86+
87+
let request = new Request(url, requestInit);
88+
89+
for (const fn of interceptors.request.fns) {
90+
if (fn) {
91+
request = await fn(request, opts);
92+
}
93+
}
94+
95+
// fetch must be assigned here, otherwise it would throw the error:
96+
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
97+
const _fetch = opts.fetch!;
98+
let response = await _fetch(request);
99+
100+
for (const fn of interceptors.response.fns) {
101+
if (fn) {
102+
response = await fn(response, request, opts);
103+
}
104+
}
105+
106+
const result = {
107+
request,
108+
response,
109+
};
110+
111+
if (response.ok) {
112+
const parseAs =
113+
(opts.parseAs === 'auto'
114+
? getParseAs(response.headers.get('Content-Type'))
115+
: opts.parseAs) ?? 'json';
116+
117+
if (
118+
response.status === 204 ||
119+
response.headers.get('Content-Length') === '0'
120+
) {
121+
let emptyData: any;
122+
switch (parseAs) {
123+
case 'arrayBuffer':
124+
case 'blob':
125+
case 'text':
126+
emptyData = await response[parseAs]();
127+
break;
128+
case 'formData':
129+
emptyData = new FormData();
130+
break;
131+
case 'stream':
132+
emptyData = response.body;
133+
break;
134+
case 'json':
135+
default:
136+
emptyData = {};
137+
break;
138+
}
139+
return opts.responseStyle === 'data'
140+
? emptyData
141+
: {
142+
data: emptyData,
143+
...result,
144+
};
145+
}
146+
147+
let data: any;
148+
switch (parseAs) {
149+
case 'arrayBuffer':
150+
case 'blob':
151+
case 'formData':
152+
case 'json':
153+
case 'text':
154+
data = await response[parseAs]();
155+
break;
156+
case 'stream':
157+
return opts.responseStyle === 'data'
158+
? response.body
159+
: {
160+
data: response.body,
161+
...result,
162+
};
163+
}
164+
165+
if (parseAs === 'json') {
166+
if (opts.responseValidator) {
167+
await opts.responseValidator(data);
168+
}
169+
170+
if (opts.responseTransformer) {
171+
data = await opts.responseTransformer(data);
172+
}
173+
}
174+
175+
return opts.responseStyle === 'data'
176+
? data
177+
: {
178+
data,
179+
...result,
180+
};
181+
}
182+
183+
const textError = await response.text();
184+
let jsonError: unknown;
185+
186+
try {
187+
jsonError = JSON.parse(textError);
188+
} catch {
189+
// noop
190+
}
191+
192+
const error = jsonError ?? textError;
193+
let finalError = error;
194+
195+
for (const fn of interceptors.error.fns) {
196+
if (fn) {
197+
finalError = (await fn(error, response, request, opts)) as string;
198+
}
199+
}
200+
201+
finalError = finalError || ({} as string);
202+
203+
if (opts.throwOnError) {
204+
throw finalError;
205+
}
206+
207+
// TODO: we probably want to return error and improve types
208+
return opts.responseStyle === 'data'
209+
? undefined
210+
: {
211+
error: finalError,
212+
...result,
213+
};
214+
};
215+
216+
const makeMethodFn =
217+
(method: Uppercase<HttpMethod>) => (options: RequestOptions) =>
218+
request({ ...options, method });
219+
220+
const makeSseFn =
221+
(method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
222+
const { opts, url } = await beforeRequest(options);
223+
return createSseClient({
224+
...opts,
225+
body: opts.body as BodyInit | null | undefined,
226+
headers: opts.headers as unknown as Record<string, string>,
227+
method,
228+
onRequest: async (url, init) => {
229+
let request = new Request(url, init);
230+
for (const fn of interceptors.request.fns) {
231+
if (fn) {
232+
request = await fn(request, opts);
233+
}
234+
}
235+
return request;
236+
},
237+
url,
238+
});
239+
};
240+
241+
return {
242+
buildUrl,
243+
connect: makeMethodFn('CONNECT'),
244+
delete: makeMethodFn('DELETE'),
245+
get: makeMethodFn('GET'),
246+
getConfig,
247+
head: makeMethodFn('HEAD'),
248+
interceptors,
249+
options: makeMethodFn('OPTIONS'),
250+
patch: makeMethodFn('PATCH'),
251+
post: makeMethodFn('POST'),
252+
put: makeMethodFn('PUT'),
253+
request,
254+
setConfig,
255+
sse: {
256+
connect: makeSseFn('CONNECT'),
257+
delete: makeSseFn('DELETE'),
258+
get: makeSseFn('GET'),
259+
head: makeSseFn('HEAD'),
260+
options: makeSseFn('OPTIONS'),
261+
patch: makeSseFn('PATCH'),
262+
post: makeSseFn('POST'),
263+
put: makeSseFn('PUT'),
264+
trace: makeSseFn('TRACE'),
265+
},
266+
trace: makeMethodFn('TRACE'),
267+
} as Client;
268+
};
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// This file is auto-generated by @hey-api/openapi-ts
2+
3+
export type { Auth } from '../core/auth.gen';
4+
export type { QuerySerializerOptions } from '../core/bodySerializer.gen';
5+
export {
6+
formDataBodySerializer,
7+
jsonBodySerializer,
8+
urlSearchParamsBodySerializer,
9+
} from '../core/bodySerializer.gen';
10+
export { buildClientParams } from '../core/params.gen';
11+
export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen';
12+
export { createClient } from './client.gen';
13+
export type {
14+
Client,
15+
ClientOptions,
16+
Config,
17+
CreateClientConfig,
18+
Options,
19+
OptionsLegacyParser,
20+
RequestOptions,
21+
RequestResult,
22+
ResolvedRequestOptions,
23+
ResponseStyle,
24+
TDataShape,
25+
} from './types.gen';
26+
export { createConfig, mergeHeaders } from './utils.gen';

0 commit comments

Comments
 (0)