@basmilius/http-client 1.13.0 → 2.1.0

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.
Files changed (90) hide show
  1. package/README.md +12 -34
  2. package/dist/decorator/dto/clone.d.ts +0 -3
  3. package/dist/decorator/dto/fill.d.ts +0 -3
  4. package/dist/decorator/dto/helper/areEqual.d.ts +0 -4
  5. package/dist/decorator/dto/helper/assertDto.d.ts +0 -3
  6. package/dist/decorator/dto/helper/cloneDto.d.ts +0 -3
  7. package/dist/decorator/dto/helper/executeIfDtoDirtyAndMarkClean.d.ts +0 -3
  8. package/dist/decorator/dto/helper/isDto.d.ts +0 -3
  9. package/dist/decorator/dto/helper/isDtoClean.d.ts +0 -3
  10. package/dist/decorator/dto/helper/isDtoDirty.d.ts +0 -3
  11. package/dist/decorator/dto/helper/relateDtoTo.d.ts +0 -3
  12. package/dist/decorator/dto/helper/relateValueTo.d.ts +0 -3
  13. package/dist/decorator/dto/helper/trackDto.d.ts +0 -3
  14. package/dist/decorator/dto/helper/unrelateDtoFrom.d.ts +0 -3
  15. package/dist/decorator/dto/helper/unrelateValueFrom.d.ts +0 -3
  16. package/dist/decorator/dto/index.d.ts +1 -4
  17. package/dist/decorator/dto/toJSON.d.ts +0 -3
  18. package/dist/decorator/index.d.ts +1 -1
  19. package/dist/index.js +4 -0
  20. package/dist/{http-client.js.map → index.js.map} +2 -2
  21. package/package.json +14 -13
  22. package/src/adapter/HttpAdapter.ts +67 -0
  23. package/src/adapter/index.ts +1 -0
  24. package/src/decorator/adapter.ts +10 -0
  25. package/src/decorator/bound.ts +5 -0
  26. package/src/decorator/debounce.ts +30 -0
  27. package/src/decorator/dto/arrayProxy.ts +65 -0
  28. package/src/decorator/dto/classProxy.ts +49 -0
  29. package/src/decorator/dto/clone.ts +24 -0
  30. package/src/decorator/dto/constant.ts +7 -0
  31. package/src/decorator/dto/fill.ts +18 -0
  32. package/src/decorator/dto/helper/areEqual.ts +13 -0
  33. package/src/decorator/dto/helper/assertDto.ts +11 -0
  34. package/src/decorator/dto/helper/circularProtect.ts +35 -0
  35. package/src/decorator/dto/helper/cloneDto.ts +9 -0
  36. package/src/decorator/dto/helper/executeIfDtoDirtyAndMarkClean.ts +16 -0
  37. package/src/decorator/dto/helper/index.ts +37 -0
  38. package/src/decorator/dto/helper/instance.ts +5 -0
  39. package/src/decorator/dto/helper/isDto.ts +9 -0
  40. package/src/decorator/dto/helper/isDtoClean.ts +10 -0
  41. package/src/decorator/dto/helper/isDtoDirty.ts +10 -0
  42. package/src/decorator/dto/helper/markDtoClean.ts +29 -0
  43. package/src/decorator/dto/helper/markDtoDirty.ts +26 -0
  44. package/src/decorator/dto/helper/relateDtoTo.ts +13 -0
  45. package/src/decorator/dto/helper/relateValueTo.ts +22 -0
  46. package/src/decorator/dto/helper/trackDto.ts +13 -0
  47. package/src/decorator/dto/helper/triggerDto.ts +18 -0
  48. package/src/decorator/dto/helper/unrelateDtoFrom.ts +15 -0
  49. package/src/decorator/dto/helper/unrelateValueFrom.ts +22 -0
  50. package/src/decorator/dto/index.ts +78 -0
  51. package/src/decorator/dto/instance.ts +33 -0
  52. package/src/decorator/dto/instanceProxy.ts +89 -0
  53. package/src/decorator/dto/map.ts +4 -0
  54. package/src/decorator/dto/refProxy.ts +61 -0
  55. package/src/decorator/dto/serialize/deserialize.ts +5 -0
  56. package/src/decorator/dto/serialize/deserializeArray.ts +5 -0
  57. package/src/decorator/dto/serialize/deserializeDateTime.ts +6 -0
  58. package/src/decorator/dto/serialize/deserializeDto.ts +28 -0
  59. package/src/decorator/dto/serialize/deserializeObject.ts +9 -0
  60. package/src/decorator/dto/serialize/deserializeUnknown.ts +31 -0
  61. package/src/decorator/dto/serialize/index.ts +7 -0
  62. package/src/decorator/dto/serialize/isSerializedDateTime.ts +5 -0
  63. package/src/decorator/dto/serialize/isSerializedDto.ts +5 -0
  64. package/src/decorator/dto/serialize/serialize.ts +5 -0
  65. package/src/decorator/dto/serialize/serializeArray.ts +19 -0
  66. package/src/decorator/dto/serialize/serializeDateTime.ts +9 -0
  67. package/src/decorator/dto/serialize/serializeDto.ts +21 -0
  68. package/src/decorator/dto/serialize/serializeObject.ts +9 -0
  69. package/src/decorator/dto/serialize/serializeUnknown.ts +34 -0
  70. package/src/decorator/dto/serialize/types.ts +3 -0
  71. package/src/decorator/dto/serialize/uuid.ts +3 -0
  72. package/src/decorator/dto/symbols.ts +11 -0
  73. package/src/decorator/dto/toJSON.ts +20 -0
  74. package/src/decorator/index.ts +31 -0
  75. package/src/dto/BlobResponse.ts +20 -0
  76. package/src/dto/Paginated.ts +38 -0
  77. package/src/dto/RequestError.ts +33 -0
  78. package/src/dto/ValidationError.ts +38 -0
  79. package/src/dto/index.ts +4 -0
  80. package/src/http/BaseResponse.ts +31 -0
  81. package/src/http/BaseService.ts +8 -0
  82. package/src/http/HttpClient.ts +41 -0
  83. package/src/http/QueryString.ts +75 -0
  84. package/src/http/RequestBuilder.ts +222 -0
  85. package/src/http/helpers.ts +17 -0
  86. package/src/http/index.ts +19 -0
  87. package/src/index.ts +5 -0
  88. package/src/type/index.ts +74 -0
  89. package/LICENSE +0 -21
  90. package/dist/http-client.js +0 -1095
@@ -0,0 +1,222 @@
1
+ import { DateTime } from 'luxon';
2
+ import { HttpAdapter } from '../adapter';
3
+ import { BlobResponse, Paginated, RequestError } from '../dto';
4
+ import type { HttpMethod, HttpStatusCode } from '../type';
5
+ import BaseResponse from './BaseResponse';
6
+ import HttpClient from './HttpClient';
7
+ import type QueryString from './QueryString';
8
+
9
+ export default class RequestBuilder {
10
+ get client(): HttpClient {
11
+ return this.#client;
12
+ }
13
+
14
+ get options(): RequestInit {
15
+ return this.#options;
16
+ }
17
+
18
+ get path(): string {
19
+ return this.#path;
20
+ }
21
+
22
+ set path(value: string) {
23
+ this.#path = value;
24
+ }
25
+
26
+ get query(): QueryString | null {
27
+ return this.#query;
28
+ }
29
+
30
+ set query(value: QueryString | null) {
31
+ this.#query = value;
32
+ }
33
+
34
+ readonly #client: HttpClient;
35
+ #path: string;
36
+ #options: RequestInit = {};
37
+ #query: QueryString | null = null;
38
+
39
+ constructor(path: string, client?: HttpClient) {
40
+ this.#client = client ?? HttpClient.instance;
41
+ this.#options.cache = 'no-cache';
42
+ this.#options.method = 'GET';
43
+ this.#path = path;
44
+ }
45
+
46
+ public bearerToken(token?: string): RequestBuilder {
47
+ token = token ?? this.#client.authToken;
48
+
49
+ if (token) {
50
+ return this.header('Authorization', `Bearer ${token}`);
51
+ }
52
+
53
+ if (this.#options.headers && 'Authorization' in this.#options.headers) {
54
+ delete this.#options.headers['Authorization'];
55
+ }
56
+
57
+ return this;
58
+ }
59
+
60
+ public body(body: BodyInit | FormData | object | null, contentType: string | null = 'application/octet-stream'): RequestBuilder {
61
+ if (body instanceof FormData) {
62
+ // note: this allows browsers to set formdata with their custom boundary.
63
+ contentType = null;
64
+ } else if (Array.isArray(body) || typeof body === 'object') {
65
+ body = JSON.stringify(body);
66
+ contentType = 'application/json';
67
+ }
68
+
69
+ this.#options.body = body;
70
+
71
+ if (contentType !== null) {
72
+ return this.header('Content-Type', contentType);
73
+ }
74
+
75
+ return this;
76
+ }
77
+
78
+ public header(name: string, value: string): RequestBuilder {
79
+ this.#options.headers = this.#options.headers || {};
80
+ this.#options.headers[name] = value;
81
+
82
+ return this;
83
+ }
84
+
85
+ public method(method: HttpMethod): RequestBuilder {
86
+ this.#options.method = method.toUpperCase();
87
+
88
+ return this;
89
+ }
90
+
91
+ public queryString(queryString: QueryString): RequestBuilder {
92
+ this.#query = queryString;
93
+
94
+ return this;
95
+ }
96
+
97
+ public signal(signal: AbortSignal | null = null): RequestBuilder {
98
+ this.#options.signal = signal;
99
+
100
+ return this;
101
+ }
102
+
103
+ public async fetch<TResult>(): Promise<TResult> {
104
+ return this.#execute()
105
+ .then(r => r.json());
106
+ }
107
+
108
+ public async fetchBlob(): Promise<BlobResponse> {
109
+ let response = await this.#execute();
110
+
111
+ if (response.status !== 200) {
112
+ const data = await response.json();
113
+
114
+ if ('code' in data && 'error' in data && 'error_description' in data) {
115
+ throw new RequestError(data.code, data.error, data.error_description, response.status as HttpStatusCode);
116
+ }
117
+
118
+ throw new RequestError(-1, 'failed_without_info', 'Request failed without any information from the backend.', response.status as HttpStatusCode);
119
+ }
120
+
121
+ let filename = response.headers.has('content-disposition')
122
+ ? HttpAdapter.parseFileNameFromContentDispositionHeader(response.headers.get('content-disposition'))
123
+ : `download-${DateTime.now().toFormat('yyyy-MM-dd HH-mm-ss')}`;
124
+
125
+ return new BlobResponse(
126
+ await response.blob(),
127
+ filename
128
+ );
129
+ }
130
+
131
+ public async run<TResult extends {}>(): Promise<BaseResponse<TResult>> {
132
+ const {data, response} = await this.#executeSafe<TResult>();
133
+
134
+ return new BaseResponse(data, response);
135
+ }
136
+
137
+ public async runAdapter<TResult extends {}>(adapterMethod: (item: object) => TResult): Promise<BaseResponse<TResult>> {
138
+ const {data, response} = await this.#executeSafe<TResult>();
139
+
140
+ return new BaseResponse(adapterMethod(data), response);
141
+ }
142
+
143
+ public async runArrayAdapter<TResult extends {}>(adapterMethod: (item: object) => TResult): Promise<BaseResponse<TResult[]>> {
144
+ return this.runAdapter<TResult[]>((data: []) => data.map(adapterMethod));
145
+ }
146
+
147
+ public async runEmpty(): Promise<BaseResponse<never>> {
148
+ return await this.#executeSafe<never>();
149
+ }
150
+
151
+ public async runPaginatedAdapter<TResult extends {}>(adapterMethod: (item: object) => TResult): Promise<BaseResponse<Paginated<TResult>>> {
152
+ return this.runAdapter<Paginated<TResult>>(response => HttpAdapter.parsePaginatedAdapter(response, adapterMethod));
153
+ }
154
+
155
+ public async runData<TResult>(): Promise<BaseResponse<TResult>> {
156
+ return await this.#executeSafe<TResult>();
157
+ }
158
+
159
+ public async runDataKey<TResult extends object, TKey extends keyof TResult = keyof TResult>(key: TKey): Promise<BaseResponse<TResult[TKey]>> {
160
+ const {data, response} = await this.#executeSafe<TResult>();
161
+
162
+ return new BaseResponse(data[key] as TResult[TKey], response);
163
+ }
164
+
165
+ public async runStatusCode(): Promise<HttpStatusCode> {
166
+ const response = await this.#executeSafe<never>();
167
+
168
+ return response.statusCode;
169
+ }
170
+
171
+ async #execute(): Promise<Response> {
172
+ let path = this.path;
173
+
174
+ if (this.query !== null) {
175
+ path += `?${this.query.build()}`;
176
+ }
177
+
178
+ return await fetch(this.client.baseUrl + path, this.options);
179
+ }
180
+
181
+ async #executeSafe<TResult>(): Promise<BaseResponse<TResult>> {
182
+ return await this
183
+ .#execute()
184
+ .then(response => RequestBuilder.#handleResponse<TResult>(response, this.client.dataField));
185
+ }
186
+
187
+ static async #handleResponse<TResult>(response: Response, dataField: boolean): Promise<BaseResponse<TResult | null>> {
188
+ if (response.status === 204) {
189
+ return new BaseResponse(null, response);
190
+ }
191
+
192
+ if (response.headers.has('content-type') && response.headers.get('content-type').startsWith('application/json')) {
193
+ const data = await response.json();
194
+
195
+ if ('code' in data && 'error' in data && 'error_description' in data) {
196
+ if ('errors' in data) {
197
+ throw HttpAdapter.parseValidationError(data);
198
+ }
199
+
200
+ throw HttpAdapter.parseRequestError(data, response.status as HttpStatusCode);
201
+ }
202
+
203
+ if (dataField && 'data' in data) {
204
+ return new BaseResponse(data.data as TResult, response);
205
+ }
206
+
207
+ return new BaseResponse(data, response);
208
+ }
209
+
210
+ if (response.status === 401 || response.status === 403) {
211
+ return new BaseResponse(null, response);
212
+ }
213
+
214
+ const data = await response.text();
215
+
216
+ if (data.length === 0 && response.status >= 200 && response.status < 300) {
217
+ return new BaseResponse(null, response);
218
+ }
219
+
220
+ throw new RequestError(-1, 'not_a_json_response', 'The response was not a JSON response.', response.status as HttpStatusCode);
221
+ }
222
+ }
@@ -0,0 +1,17 @@
1
+ import { RequestError, ValidationError } from '../dto';
2
+
3
+ export function isRequestError(obj: unknown): obj is RequestError {
4
+ return obj instanceof RequestError;
5
+ }
6
+
7
+ export function isUnsanctionedRequest(statusCode: unknown): boolean {
8
+ if (statusCode instanceof RequestError) {
9
+ statusCode = statusCode.statusCode;
10
+ }
11
+
12
+ return statusCode === 403 || statusCode === 401;
13
+ }
14
+
15
+ export function isValidationError(obj: unknown): obj is ValidationError {
16
+ return obj instanceof ValidationError;
17
+ }
@@ -0,0 +1,19 @@
1
+ import BaseResponse from './BaseResponse';
2
+ import BaseService from './BaseService';
3
+ import HttpClient from './HttpClient';
4
+ import QueryString from './QueryString';
5
+ import RequestBuilder from './RequestBuilder';
6
+
7
+ export {
8
+ BaseResponse,
9
+ BaseService,
10
+ HttpClient,
11
+ QueryString,
12
+ RequestBuilder
13
+ };
14
+
15
+ export {
16
+ isRequestError,
17
+ isUnsanctionedRequest,
18
+ isValidationError
19
+ } from './helpers';
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './adapter';
2
+ export * from './decorator';
3
+ export * from './dto';
4
+ export * from './http';
5
+ export type * from './type';
@@ -0,0 +1,74 @@
1
+ export type HttpMethod =
2
+ | 'connect'
3
+ | 'delete'
4
+ | 'get'
5
+ | 'head'
6
+ | 'options'
7
+ | 'patch'
8
+ | 'post'
9
+ | 'put'
10
+ | 'trace';
11
+
12
+ export type HttpStatusCode =
13
+ | 100 // continue
14
+ | 101 // switching protocols
15
+ | 102 // processing
16
+ | 200 // ok
17
+ | 201 // created
18
+ | 202 // accepted
19
+ | 203 // non authoritative information
20
+ | 204 // no content
21
+ | 205 // reset content
22
+ | 206 // partial content
23
+ | 207 // multi status
24
+ | 208 // already reported
25
+ | 226 // im used
26
+ | 300 // multiple choices
27
+ | 301 // moved permanently
28
+ | 302 // found
29
+ | 303 // see other
30
+ | 304 // not modified
31
+ | 305 // use proxy
32
+ | 306 // switch proxy
33
+ | 307 // temporary redirect
34
+ | 308 // permanent redirect
35
+ | 400 // bad request
36
+ | 401 // unauthorized
37
+ | 402 // payment required
38
+ | 403 // forbidden
39
+ | 404 // not found
40
+ | 405 // method not allowed
41
+ | 406 // not acceptable
42
+ | 407 // proxy authentication required
43
+ | 408 // request timeout
44
+ | 409 // conflict
45
+ | 410 // gone
46
+ | 411 // length required
47
+ | 412 // precondition failed
48
+ | 413 // payload too large
49
+ | 414 // uri too long
50
+ | 415 // unsupported media type
51
+ | 416 // range not satisfiable
52
+ | 417 // expectation failed
53
+ | 418 // i am a teapot
54
+ | 421 // misdirected request
55
+ | 422 // unprocessable entity
56
+ | 423 // locked
57
+ | 424 // failed dependency
58
+ | 426 // upgrade required
59
+ | 428 // precondition required
60
+ | 429 // too many requests
61
+ | 431 // request header fields too large
62
+ | 451 // unavailable for legal reasons
63
+ | 500 // internal server error
64
+ | 501 // not implemented
65
+ | 502 // bad gateway
66
+ | 503 // service unavailable
67
+ | 504 // gateway timeout
68
+ | 505 // http version not supported
69
+ | 506 // variant also negotiates
70
+ | 507 // insufficient storage
71
+ | 508 // loop detected
72
+ | 510 // not extended
73
+ | 511 // network authentication required
74
+ ;
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Bas Milius
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.