@hapaul/api 0.1.0 → 0.1.1

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
@@ -2239,7 +2239,7 @@ declare class ApiClient {
2239
2239
  post<T extends PostPaths>(path: T, ...params: PostParams<T>): Promise<ResponseData<T, 'post'>>;
2240
2240
  put<T extends PutPaths>(path: T, ...params: PutParams<T>): Promise<ResponseData<T, 'put'>>;
2241
2241
  patch<T extends PatchPaths>(path: T, ...params: PatchParams<T>): Promise<ResponseData<T, 'patch'>>;
2242
- delete<T extends DeletePaths>(path: T, ...params: DeleteParams<T>): Promise<ParseAsResponse<SuccessResponse<ResponseObjectMap<paths[T]["delete"]>, `${string}/${string}`>, MaybeOptionalInit<paths[T], "delete">>>;
2242
+ delete<T extends DeletePaths>(path: T, ...params: DeleteParams<T>): Promise<ResponseData<T, 'delete'>>;
2243
2243
  handleResponse<D extends {
2244
2244
  data: unknown;
2245
2245
  } | {
package/package.json CHANGED
@@ -1,9 +1,11 @@
1
1
  {
2
2
  "name": "@hapaul/api",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "",
5
5
  "type": "module",
6
- "files": ["dist"],
6
+ "files": [
7
+ "dist"
8
+ ],
7
9
  "main": "./dist/index.js",
8
10
  "module": "./dist/index.js",
9
11
  "exports": {
@@ -1,420 +0,0 @@
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
- //#region index.ts
372
- var ApiClient = class ApiClient {
373
- client;
374
- baseUrl;
375
- showLoading;
376
- showMessage;
377
- handleMessage;
378
- constructor(config) {
379
- this.baseUrl = config?.baseUrl ?? "";
380
- this.showLoading = config?.showLoading ?? true;
381
- this.showMessage = config?.showMessage ?? true;
382
- this.handleMessage = config?.handleMessage ?? ((error) => error.message);
383
- this.client = createClient({ baseUrl: this.baseUrl });
384
- }
385
- config(config) {
386
- const newConfig = {
387
- ...this.config,
388
- ...config
389
- };
390
- return new ApiClient(newConfig);
391
- }
392
- async get(path, ...params) {
393
- const { data, error } = await this.client.GET(path, ...params);
394
- return this.handleResponse(data, error);
395
- }
396
- async post(path, ...params) {
397
- const { data, error } = await this.client.POST(path, ...params);
398
- return this.handleResponse(data, error);
399
- }
400
- async put(path, ...params) {
401
- const { data, error } = await this.client.PUT(path, ...params);
402
- return this.handleResponse(data, error);
403
- }
404
- async patch(path, ...params) {
405
- const { data, error } = await this.client.PATCH(path, ...params);
406
- return this.handleResponse(data, error);
407
- }
408
- async delete(path, ...params) {
409
- const { data, error } = await this.client.DELETE(path, ...params);
410
- return this.handleResponse(data, error);
411
- }
412
- async handleResponse(data, error) {
413
- if (data) if ("code" in data) return Promise.reject(data);
414
- else return Promise.resolve(data);
415
- else return Promise.reject(error);
416
- }
417
- };
418
-
419
- //#endregion
420
- export { ApiClient };