@hapaul/api 0.1.3 → 0.1.4

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 & {
@@ -2202,41 +2238,52 @@ type InitParam<Init> = RequiredKeysOf<Init> extends never ? [(Init & {
2202
2238
  type Methods = 'get' | 'post' | 'put' | 'patch' | 'delete';
2203
2239
  type RequestParams<T extends PathsWithMethod<paths, M>, M extends Methods> = InitParam<MaybeOptionalInit<paths[T], M>>;
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
+ interface ClientConfig<C = {}> {
2207
2243
  baseUrl?: string;
2208
- custom?: any;
2244
+ custom?: C;
2209
2245
  }
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
- }>;
2246
+ interface RequestConfig<C> extends ClientConfig<C> {}
2247
+ type RequestResponse<T extends PathsWithMethod<paths, M>, M extends Methods> = Promise<{
2248
+ data: ResponseData<T, M>;
2249
+ error: ResponseError<T, M>;
2250
+ response: Response;
2251
+ }>;
2252
+ interface Middleware<C> {
2253
+ onRequest?: (config: RequestConfig<C>) => RequestConfig<C> | Promise<RequestConfig<C>>;
2254
+ onResponse?: (config: RequestConfig<C>, response: Response) => Response | Promise<Response>;
2216
2255
  }
2217
- declare class ApiClient {
2218
- private client;
2256
+ declare class Client<C = {}> {
2257
+ private middlewares;
2219
2258
  private baseUrl;
2220
2259
  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
- }>;
2260
+ use(middleware: Middleware<C>): void;
2261
+ request<T extends PathsWithMethod<paths, M>, M extends Methods>(params: {
2262
+ method: M;
2263
+ path: T;
2264
+ } & RequestParams<T, M>, config?: RequestConfig<C>): RequestResponse<T, M>;
2265
+ get<T extends PathsWithMethod<paths, 'get'>>(params: {
2266
+ path: T;
2267
+ } & RequestParams<T, 'get'>, config?: RequestConfig<C>): RequestResponse<T, 'get'>;
2268
+ post<T extends PathsWithMethod<paths, 'post'>>(params: {
2269
+ path: T;
2270
+ } & RequestParams<T, 'post'>, config?: RequestConfig<C>): RequestResponse<T, 'post'>;
2271
+ put<T extends PathsWithMethod<paths, 'put'>>(params: {
2272
+ path: T;
2273
+ } & RequestParams<T, 'put'>, config?: RequestConfig<C>): RequestResponse<T, 'put'>;
2274
+ patch<T extends PathsWithMethod<paths, 'patch'>>(params: {
2275
+ path: T;
2276
+ } & RequestParams<T, 'patch'>, config?: RequestConfig<C>): RequestResponse<T, 'patch'>;
2277
+ delete<T extends PathsWithMethod<paths, 'delete'>>(params: {
2278
+ path: T;
2279
+ } & RequestParams<T, 'delete'>, config?: RequestConfig<C>): RequestResponse<T, 'delete'>;
2280
+ beforeRequest(params: {
2281
+ config: RequestConfig<C>;
2282
+ }): Promise<RequestConfig<C>>;
2283
+ afterResponse(params: {
2284
+ config: ClientConfig<C>;
2285
+ response: Response;
2286
+ }): Promise<Response>;
2240
2287
  }
2241
2288
  //#endregion
2242
- export { ApiClient, ApiClientInstance, ClientConfig, RequestConfig };
2289
+ export { Client, ClientConfig, Middleware, RequestConfig, RequestResponse };
package/dist/index.js CHANGED
@@ -1,425 +1,97 @@
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
31
- };
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
49
- });
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;
61
- 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
- }
113
- }
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
- return {
128
- data: await response[parseAs](),
129
- response
130
- };
131
- }
132
- let error = await response.text();
133
- try {
134
- error = JSON.parse(error);
135
- } catch {}
136
- return {
137
- error,
138
- response
139
- };
140
- }
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();
343
- }
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);
362
- }
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
1
  //#region index.ts
372
- var ApiClient = class ApiClient {
373
- client;
2
+ var Client = class {
3
+ middlewares;
374
4
  baseUrl;
375
5
  constructor(config) {
6
+ this.middlewares = [];
376
7
  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);
385
8
  }
386
9
  use(middleware) {
387
- this.client.use(middleware);
10
+ this.middlewares.push(middleware);
388
11
  }
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({
12
+ async request(params, config) {
13
+ config = await this.beforeRequest({ config });
14
+ const baseUrl = config.baseUrl ?? this.baseUrl;
15
+ const url = baseUrl + params.path;
16
+ try {
17
+ let response = await fetch(url);
18
+ response = await this.afterResponse({
394
19
  config,
395
- data,
396
- error
20
+ response
397
21
  });
398
- } };
399
- }
400
- get(path, ...params) {
401
- return this.request("get", path, ...params);
402
- }
403
- post(path, ...params) {
404
- return this.request("post", path, ...params);
405
- }
406
- put(path, ...params) {
407
- return this.request("put", path, ...params);
408
- }
409
- patch(path, ...params) {
410
- return this.request("patch", path, ...params);
22
+ const { status } = response;
23
+ let data;
24
+ let error;
25
+ let isOk = true;
26
+ const assign = (value) => {
27
+ if (isOk) data = value;
28
+ else error = value;
29
+ };
30
+ if (status >= 200 && status < 300) isOk = true;
31
+ else if (status >= 400) isOk = false;
32
+ const contentType = response.headers.get("Content-Type") || "application/json";
33
+ switch (contentType) {
34
+ case "application/json":
35
+ assign(await response.json());
36
+ break;
37
+ case "text":
38
+ assign(await response.text());
39
+ break;
40
+ case "arrayBuffer":
41
+ assign(await response.arrayBuffer());
42
+ break;
43
+ default: assign(await response.bytes());
44
+ }
45
+ return {
46
+ data,
47
+ error,
48
+ response
49
+ };
50
+ } catch (error) {
51
+ throw error;
52
+ }
411
53
  }
412
- delete(path, ...params) {
413
- return this.request("delete", path, ...params);
54
+ get(params, config) {
55
+ return this.request({
56
+ method: "get",
57
+ ...params
58
+ }, config);
59
+ }
60
+ post(params, config) {
61
+ return this.request({
62
+ method: "post",
63
+ ...params
64
+ }, config);
65
+ }
66
+ put(params, config) {
67
+ return this.request({
68
+ method: "put",
69
+ ...params
70
+ }, config);
71
+ }
72
+ patch(params, config) {
73
+ return this.request({
74
+ method: "patch",
75
+ ...params
76
+ }, config);
77
+ }
78
+ delete(params, config) {
79
+ return this.request({
80
+ method: "delete",
81
+ ...params
82
+ }, config);
83
+ }
84
+ async beforeRequest(params) {
85
+ let config = params.config;
86
+ for (const middleware of this.middlewares) config = await middleware.onRequest?.(config);
87
+ return config;
414
88
  }
415
- async beforeRequest(params) {}
416
89
  async afterResponse(params) {
417
- return {
418
- data: params.data,
419
- error: params.error
420
- };
90
+ let response = params.response;
91
+ for (const middleware of this.middlewares) response = await middleware.onResponse?.(params.config, response);
92
+ return response;
421
93
  }
422
94
  };
423
95
 
424
96
  //#endregion
425
- export { ApiClient };
97
+ 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.4",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "files": [