@hapaul/api 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { MaybeOptionalInit, Middleware, ParseAsResponse } from "openapi-fetch";
2
- import { ErrorResponse, PathsWithMethod, ResponseObjectMap, SuccessResponse } from "openapi-typescript-helpers";
1
+ import { ErrorResponse, FilterKeys, IsOperationRequestBodyOptional, OperationRequestBodyContent, PathsWithMethod, ResponseObjectMap, SuccessResponse } from "openapi-typescript-helpers";
3
2
 
4
3
  //#region schema.d.ts
5
4
 
@@ -2192,6 +2191,43 @@ interface operations {
2192
2191
  }
2193
2192
  //#endregion
2194
2193
  //#region index.d.ts
2194
+ interface DefaultParamsOption {
2195
+ params?: {
2196
+ query?: Record<string, unknown>;
2197
+ };
2198
+ }
2199
+ type BodyType<T = unknown> = {
2200
+ json: T;
2201
+ text: Awaited<ReturnType<Response['text']>>;
2202
+ blob: Awaited<ReturnType<Response['blob']>>;
2203
+ arrayBuffer: Awaited<ReturnType<Response['arrayBuffer']>>;
2204
+ stream: Response['body'];
2205
+ };
2206
+ type ParseAs = keyof BodyType;
2207
+ type ParseAsResponse<T, Options> = Options extends {
2208
+ parseAs: ParseAs;
2209
+ } ? BodyType<T>[Options['parseAs']] : T;
2210
+ type ParamsOption<T> = T extends {
2211
+ parameters: any;
2212
+ } ? RequiredKeysOf<T['parameters']> extends never ? {
2213
+ params?: T['parameters'];
2214
+ } : {
2215
+ params: T['parameters'];
2216
+ } : DefaultParamsOption;
2217
+ type RequestBodyOption<T> = OperationRequestBodyContent<T> extends never ? {
2218
+ body?: never;
2219
+ } : IsOperationRequestBodyOptional<T> extends true ? {
2220
+ body?: OperationRequestBodyContent<T>;
2221
+ } : {
2222
+ body: OperationRequestBodyContent<T>;
2223
+ };
2224
+ type HeadersOptions = Required<RequestInit>['headers'] | Record<string, string | number | boolean | (string | number | boolean)[] | null | undefined>;
2225
+ type RequestOptions<T> = ParamsOption<T> & RequestBodyOption<T> & {
2226
+ baseUrl?: string;
2227
+ headers?: HeadersOptions;
2228
+ };
2229
+ type FetchOptions<T> = RequestOptions<T> & Omit<RequestInit, 'body' | 'headers'>;
2230
+ type MaybeOptionalInit<Params, Location extends keyof Params> = RequiredKeysOf<FetchOptions<FilterKeys<Params, Location>>> extends never ? FetchOptions<FilterKeys<Params, Location>> | undefined : FetchOptions<FilterKeys<Params, Location>>;
2195
2231
  type RequiredKeysOfHelper<T> = { [K in keyof T]: {} extends Pick<T, K> ? never : K }[keyof T];
2196
2232
  type RequiredKeysOf<T> = RequiredKeysOfHelper<T> extends undefined ? never : RequiredKeysOfHelper<T>;
2197
2233
  type InitParam<Init> = RequiredKeysOf<Init> extends never ? [(Init & {
@@ -2200,43 +2236,43 @@ type InitParam<Init> = RequiredKeysOf<Init> extends never ? [(Init & {
2200
2236
  [key: string]: unknown;
2201
2237
  }];
2202
2238
  type Methods = 'get' | 'post' | 'put' | 'patch' | 'delete';
2203
- type RequestParams<T extends PathsWithMethod<paths, M>, M extends Methods> = InitParam<MaybeOptionalInit<paths[T], M>>;
2239
+ type RequestParams<T extends PathsWithMethod<paths, M>, M extends Methods, C> = InitParam<MaybeOptionalInit<paths[T], M> & C>;
2204
2240
  type ResponseData<T extends PathsWithMethod<paths, M>, M extends Methods> = ParseAsResponse<SuccessResponse<ResponseObjectMap<paths[T][M]>, `${string}/${string}`>, MaybeOptionalInit<paths[T], M>>;
2205
- type ErrorResponseData<T extends PathsWithMethod<paths, M>, M extends Methods> = ErrorResponse<ResponseObjectMap<paths[T][M]>, `${string}/${string}`>;
2206
- interface ClientConfig {
2241
+ type ResponseError<T extends PathsWithMethod<paths, M>, M extends Methods> = ErrorResponse<ResponseObjectMap<paths[T][M]>, `${string}/${string}`>;
2242
+ type ClientConfig = {
2207
2243
  baseUrl?: string;
2208
- custom?: any;
2209
- }
2210
- interface RequestConfig<T extends PathsWithMethod<paths, M>, M extends Methods> extends ClientConfig {}
2211
- interface ApiClientInstance<T extends PathsWithMethod<paths, M>, M extends Methods> {
2212
- send: (config?: RequestConfig<T, M>) => Promise<{
2213
- data: ResponseData<T, M>;
2214
- error: ErrorResponseData<T, M>;
2215
- }>;
2244
+ };
2245
+ type RequestConfig<T extends PathsWithMethod<paths, M>, M extends Methods, C = {}> = ClientConfig & {
2246
+ method: M;
2247
+ path: T;
2248
+ } & MaybeOptionalInit<paths[T], M> & C;
2249
+ type RequestResponse<T extends PathsWithMethod<paths, M>, M extends Methods> = Promise<{
2250
+ data: ResponseData<T, M>;
2251
+ error: ResponseError<T, M>;
2252
+ response: Response;
2253
+ }>;
2254
+ interface Middleware<C> {
2255
+ onRequest?: (config: RequestConfig<any, any, C>) => RequestConfig<any, any, C> | Promise<RequestConfig<any, any, C>>;
2256
+ onResponse?: (config: RequestConfig<any, any, C>, response: Response) => Response | Promise<Response>;
2216
2257
  }
2217
- declare class ApiClient {
2218
- private client;
2258
+ declare class Client<C = {}> {
2259
+ private middlewares;
2219
2260
  private baseUrl;
2220
2261
  constructor(config?: ClientConfig);
2221
- config(config?: ClientConfig): ApiClient;
2222
- use(middleware: Middleware): void;
2223
- request<T extends PathsWithMethod<paths, M>, M extends Methods>(method: M, path: T, ...params: RequestParams<T, M>): ApiClientInstance<T, M>;
2224
- get<T extends PathsWithMethod<paths, 'get'>>(path: T, ...params: RequestParams<T, 'get'>): ApiClientInstance<T, 'get'>;
2225
- post<T extends PathsWithMethod<paths, 'post'>>(path: T, ...params: RequestParams<T, 'post'>): ApiClientInstance<T, 'post'>;
2226
- put<T extends PathsWithMethod<paths, 'put'>>(path: T, ...params: RequestParams<T, 'put'>): ApiClientInstance<T, 'put'>;
2227
- patch<T extends PathsWithMethod<paths, 'patch'>>(path: T, ...params: RequestParams<T, 'patch'>): ApiClientInstance<T, 'patch'>;
2228
- delete<T extends PathsWithMethod<paths, 'delete'>>(path: T, ...params: RequestParams<T, 'delete'>): ApiClientInstance<T, 'delete'>;
2229
- beforeRequest<T extends PathsWithMethod<paths, M>, M extends Methods>(params: {
2230
- config: RequestConfig<T, M>;
2231
- }): Promise<void>;
2232
- afterResponse<D, U>(params: {
2233
- config: ClientConfig;
2234
- data: D;
2235
- error: U;
2236
- }): Promise<{
2237
- data: D;
2238
- error: U;
2239
- }>;
2262
+ use(middleware: Middleware<C>): void;
2263
+ request<T extends PathsWithMethod<paths, M>, M extends Methods>(method: M, path: T, ...params: RequestParams<T, M, C>): RequestResponse<T, M>;
2264
+ get<T extends PathsWithMethod<paths, 'get'>>(path: T, params: RequestConfig<T, 'get', C>): RequestResponse<T, 'get'>;
2265
+ post<T extends PathsWithMethod<paths, 'post'>>(path: T, params: RequestConfig<T, 'post', C>): RequestResponse<T, 'post'>;
2266
+ patch<T extends PathsWithMethod<paths, 'patch'>>(path: T, params: RequestConfig<T, 'patch', C>): RequestResponse<T, 'patch'>;
2267
+ put<T extends PathsWithMethod<paths, 'put'>>(path: T, params: RequestConfig<T, 'put', C>): RequestResponse<T, 'put'>;
2268
+ delete<T extends PathsWithMethod<paths, 'delete'>>(path: T, params: RequestConfig<T, 'delete', C>): RequestResponse<T, 'delete'>;
2269
+ beforeRequest(params: {
2270
+ config: any;
2271
+ }): Promise<any>;
2272
+ afterResponse(params: {
2273
+ config: any;
2274
+ response: Response;
2275
+ }): Promise<Response>;
2240
2276
  }
2241
2277
  //#endregion
2242
- export { ApiClient, ApiClientInstance, ClientConfig, RequestConfig };
2278
+ export { Client, ClientConfig, Middleware, RequestConfig, RequestResponse };
package/dist/index.js CHANGED
@@ -1,425 +1,89 @@
1
- //#region node_modules/.pnpm/openapi-fetch@0.14.0/node_modules/openapi-fetch/dist/index.mjs
2
- const PATH_PARAM_RE = /\{[^{}]+\}/g;
3
- const supportsRequestInitExt = () => {
4
- return typeof process === "object" && Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 && process.versions.undici;
5
- };
6
- function randomID() {
7
- return Math.random().toString(36).slice(2, 11);
8
- }
9
- function createClient(clientOptions) {
10
- let { baseUrl = "", Request: CustomRequest = globalThis.Request, fetch: baseFetch = globalThis.fetch, querySerializer: globalQuerySerializer, bodySerializer: globalBodySerializer, headers: baseHeaders, requestInitExt = void 0,...baseOptions } = { ...clientOptions };
11
- requestInitExt = supportsRequestInitExt() ? requestInitExt : void 0;
12
- baseUrl = removeTrailingSlash(baseUrl);
13
- const middlewares = [];
14
- async function coreFetch(schemaPath, fetchOptions) {
15
- const { baseUrl: localBaseUrl, fetch = baseFetch, Request = CustomRequest, headers, params = {}, parseAs = "json", querySerializer: requestQuerySerializer, bodySerializer = globalBodySerializer ?? defaultBodySerializer, body,...init } = fetchOptions || {};
16
- let finalBaseUrl = baseUrl;
17
- if (localBaseUrl) finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;
18
- let querySerializer = typeof globalQuerySerializer === "function" ? globalQuerySerializer : createQuerySerializer(globalQuerySerializer);
19
- if (requestQuerySerializer) querySerializer = typeof requestQuerySerializer === "function" ? requestQuerySerializer : createQuerySerializer({
20
- ...typeof globalQuerySerializer === "object" ? globalQuerySerializer : {},
21
- ...requestQuerySerializer
22
- });
23
- const serializedBody = body === void 0 ? void 0 : bodySerializer(body, mergeHeaders(baseHeaders, headers, params.header));
24
- const finalHeaders = mergeHeaders(serializedBody === void 0 || serializedBody instanceof FormData ? {} : { "Content-Type": "application/json" }, baseHeaders, headers, params.header);
25
- const requestInit = {
26
- redirect: "follow",
27
- ...baseOptions,
28
- ...init,
29
- body: serializedBody,
30
- headers: finalHeaders
1
+ //#region index.ts
2
+ var Client = class {
3
+ middlewares;
4
+ baseUrl;
5
+ constructor(config) {
6
+ this.middlewares = [];
7
+ this.baseUrl = config?.baseUrl ?? "";
8
+ }
9
+ use(middleware) {
10
+ this.middlewares.push(middleware);
11
+ }
12
+ async request(method, path, ...params) {
13
+ let requestConfig = {
14
+ method,
15
+ path,
16
+ ...params[0]
31
17
  };
32
- let id;
33
- let options;
34
- let request = new CustomRequest(createFinalURL(schemaPath, {
35
- baseUrl: finalBaseUrl,
36
- params,
37
- querySerializer
38
- }), requestInit);
39
- let response;
40
- for (const key in init) if (!(key in request)) request[key] = init[key];
41
- if (middlewares.length) {
42
- id = randomID();
43
- options = Object.freeze({
44
- baseUrl: finalBaseUrl,
45
- fetch,
46
- parseAs,
47
- querySerializer,
48
- bodySerializer
18
+ requestConfig = await this.beforeRequest({ config: requestConfig });
19
+ method = requestConfig.method;
20
+ const baseUrl = requestConfig.baseUrl ?? this.baseUrl;
21
+ const url = baseUrl + path;
22
+ try {
23
+ const {} = params;
24
+ let response = await fetch(url, { method: method.toUpperCase() });
25
+ response = await this.afterResponse({
26
+ config: requestConfig,
27
+ response
49
28
  });
50
- for (const m of middlewares) if (m && typeof m === "object" && typeof m.onRequest === "function") {
51
- const result = await m.onRequest({
52
- request,
53
- schemaPath,
54
- params,
55
- options,
56
- id
57
- });
58
- if (result) if (result instanceof CustomRequest) request = result;
59
- else if (result instanceof Response) {
60
- response = result;
29
+ const { status } = response;
30
+ let data;
31
+ let error;
32
+ let isOk = true;
33
+ const assign = (value) => {
34
+ if (isOk) data = value;
35
+ else error = value;
36
+ };
37
+ if (status >= 200 && status < 300) isOk = true;
38
+ else if (status >= 400) isOk = false;
39
+ const contentType = response.headers.get("Content-Type") || "application/json";
40
+ switch (contentType) {
41
+ case "application/json":
42
+ assign(await response.json());
61
43
  break;
62
- } else throw new Error("onRequest: must return new Request() or Response() when modifying the request");
63
- }
64
- }
65
- if (!response) {
66
- try {
67
- response = await fetch(request, requestInitExt);
68
- } catch (error2) {
69
- let errorAfterMiddleware = error2;
70
- if (middlewares.length) for (let i = middlewares.length - 1; i >= 0; i--) {
71
- const m = middlewares[i];
72
- if (m && typeof m === "object" && typeof m.onError === "function") {
73
- const result = await m.onError({
74
- request,
75
- error: errorAfterMiddleware,
76
- schemaPath,
77
- params,
78
- options,
79
- id
80
- });
81
- if (result) {
82
- if (result instanceof Response) {
83
- errorAfterMiddleware = void 0;
84
- response = result;
85
- break;
86
- }
87
- if (result instanceof Error) {
88
- errorAfterMiddleware = result;
89
- continue;
90
- }
91
- throw new Error("onError: must return new Response() or instance of Error");
92
- }
93
- }
94
- }
95
- if (errorAfterMiddleware) throw errorAfterMiddleware;
96
- }
97
- if (middlewares.length) for (let i = middlewares.length - 1; i >= 0; i--) {
98
- const m = middlewares[i];
99
- if (m && typeof m === "object" && typeof m.onResponse === "function") {
100
- const result = await m.onResponse({
101
- request,
102
- response,
103
- schemaPath,
104
- params,
105
- options,
106
- id
107
- });
108
- if (result) {
109
- if (!(result instanceof Response)) throw new Error("onResponse: must return new Response() when modifying the response");
110
- response = result;
111
- }
112
- }
44
+ case "text":
45
+ assign(await response.text());
46
+ break;
47
+ case "arrayBuffer":
48
+ assign(await response.arrayBuffer());
49
+ break;
50
+ default: assign(await response.bytes());
113
51
  }
114
- }
115
- if (response.status === 204 || request.method === "HEAD" || response.headers.get("Content-Length") === "0") return response.ok ? {
116
- data: void 0,
117
- response
118
- } : {
119
- error: void 0,
120
- response
121
- };
122
- if (response.ok) {
123
- if (parseAs === "stream") return {
124
- data: response.body,
125
- response
126
- };
127
52
  return {
128
- data: await response[parseAs](),
53
+ data,
54
+ error,
129
55
  response
130
56
  };
57
+ } catch (error) {
58
+ throw error;
131
59
  }
132
- let error = await response.text();
133
- try {
134
- error = JSON.parse(error);
135
- } catch {}
136
- return {
137
- error,
138
- response
139
- };
140
60
  }
141
- return {
142
- request(method, url, init) {
143
- return coreFetch(url, {
144
- ...init,
145
- method: method.toUpperCase()
146
- });
147
- },
148
- GET(url, init) {
149
- return coreFetch(url, {
150
- ...init,
151
- method: "GET"
152
- });
153
- },
154
- PUT(url, init) {
155
- return coreFetch(url, {
156
- ...init,
157
- method: "PUT"
158
- });
159
- },
160
- POST(url, init) {
161
- return coreFetch(url, {
162
- ...init,
163
- method: "POST"
164
- });
165
- },
166
- DELETE(url, init) {
167
- return coreFetch(url, {
168
- ...init,
169
- method: "DELETE"
170
- });
171
- },
172
- OPTIONS(url, init) {
173
- return coreFetch(url, {
174
- ...init,
175
- method: "OPTIONS"
176
- });
177
- },
178
- HEAD(url, init) {
179
- return coreFetch(url, {
180
- ...init,
181
- method: "HEAD"
182
- });
183
- },
184
- PATCH(url, init) {
185
- return coreFetch(url, {
186
- ...init,
187
- method: "PATCH"
188
- });
189
- },
190
- TRACE(url, init) {
191
- return coreFetch(url, {
192
- ...init,
193
- method: "TRACE"
194
- });
195
- },
196
- use(...middleware) {
197
- for (const m of middleware) {
198
- if (!m) continue;
199
- if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m || "onError" in m)) throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
200
- middlewares.push(m);
201
- }
202
- },
203
- eject(...middleware) {
204
- for (const m of middleware) {
205
- const i = middlewares.indexOf(m);
206
- if (i !== -1) middlewares.splice(i, 1);
207
- }
208
- }
209
- };
210
- }
211
- function serializePrimitiveParam(name, value, options) {
212
- if (value === void 0 || value === null) return "";
213
- if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
214
- return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
215
- }
216
- function serializeObjectParam(name, value, options) {
217
- if (!value || typeof value !== "object") return "";
218
- const values = [];
219
- const joiner = {
220
- simple: ",",
221
- label: ".",
222
- matrix: ";"
223
- }[options.style] || "&";
224
- if (options.style !== "deepObject" && options.explode === false) {
225
- for (const k in value) values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));
226
- const final2 = values.join(",");
227
- switch (options.style) {
228
- case "form": return `${name}=${final2}`;
229
- case "label": return `.${final2}`;
230
- case "matrix": return `;${name}=${final2}`;
231
- default: return final2;
232
- }
233
- }
234
- for (const k in value) {
235
- const finalName = options.style === "deepObject" ? `${name}[${k}]` : k;
236
- values.push(serializePrimitiveParam(finalName, value[k], options));
237
- }
238
- const final = values.join(joiner);
239
- return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
240
- }
241
- function serializeArrayParam(name, value, options) {
242
- if (!Array.isArray(value)) return "";
243
- if (options.explode === false) {
244
- const joiner2 = {
245
- form: ",",
246
- spaceDelimited: "%20",
247
- pipeDelimited: "|"
248
- }[options.style] || ",";
249
- const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner2);
250
- switch (options.style) {
251
- case "simple": return final;
252
- case "label": return `.${final}`;
253
- case "matrix": return `;${name}=${final}`;
254
- default: return `${name}=${final}`;
255
- }
256
- }
257
- const joiner = {
258
- simple: ",",
259
- label: ".",
260
- matrix: ";"
261
- }[options.style] || "&";
262
- const values = [];
263
- for (const v of value) if (options.style === "simple" || options.style === "label") values.push(options.allowReserved === true ? v : encodeURIComponent(v));
264
- else values.push(serializePrimitiveParam(name, v, options));
265
- return options.style === "label" || options.style === "matrix" ? `${joiner}${values.join(joiner)}` : values.join(joiner);
266
- }
267
- function createQuerySerializer(options) {
268
- return function querySerializer(queryParams) {
269
- const search = [];
270
- if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
271
- const value = queryParams[name];
272
- if (value === void 0 || value === null) continue;
273
- if (Array.isArray(value)) {
274
- if (value.length === 0) continue;
275
- search.push(serializeArrayParam(name, value, {
276
- style: "form",
277
- explode: true,
278
- ...options?.array,
279
- allowReserved: options?.allowReserved || false
280
- }));
281
- continue;
282
- }
283
- if (typeof value === "object") {
284
- search.push(serializeObjectParam(name, value, {
285
- style: "deepObject",
286
- explode: true,
287
- ...options?.object,
288
- allowReserved: options?.allowReserved || false
289
- }));
290
- continue;
291
- }
292
- search.push(serializePrimitiveParam(name, value, options));
293
- }
294
- return search.join("&");
295
- };
296
- }
297
- function defaultPathSerializer(pathname, pathParams) {
298
- let nextURL = pathname;
299
- for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
300
- let name = match.substring(1, match.length - 1);
301
- let explode = false;
302
- let style = "simple";
303
- if (name.endsWith("*")) {
304
- explode = true;
305
- name = name.substring(0, name.length - 1);
306
- }
307
- if (name.startsWith(".")) {
308
- style = "label";
309
- name = name.substring(1);
310
- } else if (name.startsWith(";")) {
311
- style = "matrix";
312
- name = name.substring(1);
313
- }
314
- if (!pathParams || pathParams[name] === void 0 || pathParams[name] === null) continue;
315
- const value = pathParams[name];
316
- if (Array.isArray(value)) {
317
- nextURL = nextURL.replace(match, serializeArrayParam(name, value, {
318
- style,
319
- explode
320
- }));
321
- continue;
322
- }
323
- if (typeof value === "object") {
324
- nextURL = nextURL.replace(match, serializeObjectParam(name, value, {
325
- style,
326
- explode
327
- }));
328
- continue;
329
- }
330
- if (style === "matrix") {
331
- nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);
332
- continue;
333
- }
334
- nextURL = nextURL.replace(match, style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));
335
- }
336
- return nextURL;
337
- }
338
- function defaultBodySerializer(body, headers) {
339
- if (body instanceof FormData) return body;
340
- if (headers) {
341
- const contentType = headers.get instanceof Function ? headers.get("Content-Type") ?? headers.get("content-type") : headers["Content-Type"] ?? headers["content-type"];
342
- if (contentType === "application/x-www-form-urlencoded") return new URLSearchParams(body).toString();
61
+ get(path, params) {
62
+ return this.request("get", path, params);
343
63
  }
344
- return JSON.stringify(body);
345
- }
346
- function createFinalURL(pathname, options) {
347
- let finalURL = `${options.baseUrl}${pathname}`;
348
- if (options.params?.path) finalURL = defaultPathSerializer(finalURL, options.params.path);
349
- let search = options.querySerializer(options.params.query ?? {});
350
- if (search.startsWith("?")) search = search.substring(1);
351
- if (search) finalURL += `?${search}`;
352
- return finalURL;
353
- }
354
- function mergeHeaders(...allHeaders) {
355
- const finalHeaders = new Headers();
356
- for (const h of allHeaders) {
357
- if (!h || typeof h !== "object") continue;
358
- const iterator = h instanceof Headers ? h.entries() : Object.entries(h);
359
- for (const [k, v] of iterator) if (v === null) finalHeaders.delete(k);
360
- else if (Array.isArray(v)) for (const v2 of v) finalHeaders.append(k, v2);
361
- else if (v !== void 0) finalHeaders.set(k, v);
64
+ post(path, params) {
65
+ return this.request("post", path, params);
362
66
  }
363
- return finalHeaders;
364
- }
365
- function removeTrailingSlash(url) {
366
- if (url.endsWith("/")) return url.substring(0, url.length - 1);
367
- return url;
368
- }
369
-
370
- //#endregion
371
- //#region index.ts
372
- var ApiClient = class ApiClient {
373
- client;
374
- baseUrl;
375
- constructor(config) {
376
- this.baseUrl = config?.baseUrl ?? "";
377
- this.client = createClient({ baseUrl: this.baseUrl });
378
- }
379
- config(config) {
380
- const newConfig = {
381
- ...this.config,
382
- ...config
383
- };
384
- return new ApiClient(newConfig);
67
+ patch(path, params) {
68
+ return this.request("patch", path, params);
385
69
  }
386
- use(middleware) {
387
- this.client.use(middleware);
388
- }
389
- request(method, path, ...params) {
390
- return { send: async (config) => {
391
- await this.beforeRequest({ config });
392
- const { data, error } = await this.client.request(method, path, ...params);
393
- return this.afterResponse({
394
- config,
395
- data,
396
- error
397
- });
398
- } };
70
+ put(path, params) {
71
+ return this.request("put", path, params);
399
72
  }
400
- get(path, ...params) {
401
- return this.request("get", path, ...params);
73
+ delete(path, params) {
74
+ return this.request("delete", path, params);
402
75
  }
403
- post(path, ...params) {
404
- return this.request("post", path, ...params);
76
+ async beforeRequest(params) {
77
+ let config = params.config;
78
+ for (const middleware of this.middlewares) config = await middleware.onRequest?.(config);
79
+ return config;
405
80
  }
406
- put(path, ...params) {
407
- return this.request("put", path, ...params);
408
- }
409
- patch(path, ...params) {
410
- return this.request("patch", path, ...params);
411
- }
412
- delete(path, ...params) {
413
- return this.request("delete", path, ...params);
414
- }
415
- async beforeRequest(params) {}
416
81
  async afterResponse(params) {
417
- return {
418
- data: params.data,
419
- error: params.error
420
- };
82
+ let response = params.response;
83
+ for (const middleware of this.middlewares) response = await middleware.onResponse?.(params.config, response);
84
+ return response;
421
85
  }
422
86
  };
423
87
 
424
88
  //#endregion
425
- export { ApiClient };
89
+ export { Client };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hapaul/api",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "files": [