rest-client-sdk 6.6.0 → 7.0.0-rc.3

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.
@@ -0,0 +1,96 @@
1
+ import { convertToRecord } from '../client/headerUtils';
2
+
3
+ type SdkRequest = RequestInit & { url: string };
4
+
5
+ // type SdkResponse = Partial<Response>;
6
+ type SdkResponse = {
7
+ status: number;
8
+ headers: Record<string, string>;
9
+ };
10
+
11
+ const generateId = () =>
12
+ `rest-client-sdk|${Date.now()}-${
13
+ Math.floor(Math.random() * (9e12 - 1)) + 1e12
14
+ }`;
15
+
16
+ export type SerializableRequest = {
17
+ url: string;
18
+ method?: string;
19
+ headers?: Record<string, string>;
20
+ body?: string;
21
+ };
22
+
23
+ export type Log = {
24
+ id: string;
25
+ request?: SerializableRequest;
26
+ response?: SdkResponse;
27
+ logTimes: {
28
+ request?: number;
29
+ response?: number;
30
+ };
31
+ };
32
+
33
+ export type LoggerHistory = Array<Log>;
34
+
35
+ function serializeRequest(req: SdkRequest): SerializableRequest {
36
+ const request = { ...req }; // Make a clone, useful for doing destructive things
37
+ return {
38
+ method: request.method, // The Request Method, e.g. GET, POST, DELETE
39
+ url: request.url, // The URL
40
+ headers: request.headers ? convertToRecord(request.headers) : undefined,
41
+ body: typeof request.body === 'string' ? request.body : undefined,
42
+ };
43
+ }
44
+
45
+ // eslint-disable-next-line import/prefer-default-export
46
+ export class Logger {
47
+ #history: LoggerHistory;
48
+
49
+ get history(): LoggerHistory {
50
+ return this.#history;
51
+ }
52
+
53
+ constructor() {
54
+ this.#history = [];
55
+ }
56
+
57
+ logRequest(params: SdkRequest): string {
58
+ const log: Log = {
59
+ id: generateId(),
60
+ request: serializeRequest(params),
61
+ logTimes: { request: Date.now() },
62
+ };
63
+
64
+ this.#history.push(log);
65
+
66
+ return log.id;
67
+ }
68
+
69
+ logResponse(response: Response, requestId?: undefined | string): string {
70
+ const id = requestId || generateId();
71
+
72
+ // console.log('clone');
73
+ // const clonedResponse = response.clone(); // THIS IS THE LINE THAT CAUSES THE PROBLEM
74
+ // console.log('after clone', clonedResponse.status);
75
+
76
+ const logContent: SdkResponse = {
77
+ status: response.status, // clonedResponse.status,
78
+ headers: Object.fromEntries(response.headers),
79
+ };
80
+
81
+ const foundLogIndex = this.#history.findIndex((log) => log.id === id);
82
+
83
+ if (foundLogIndex > -1) {
84
+ this.#history[foundLogIndex].response = logContent;
85
+ this.#history[foundLogIndex].logTimes.response = Date.now();
86
+ } else {
87
+ this.#history.push({
88
+ id,
89
+ response: logContent,
90
+ logTimes: { response: Date.now() },
91
+ });
92
+ }
93
+
94
+ return id;
95
+ }
96
+ }
package/CHANGELOG.md DELETED
@@ -1,499 +0,0 @@
1
- # Changelog
2
-
3
- ## 6.6.0
4
-
5
- - Add Authorization code flow token generator
6
- - Better compatibility with the oauth spec: https://tools.ietf.org/html/rfc6749
7
- - handle oauth error even if the TokenGenerator does not extends `AbstractTokenGenator` or call `_manageOauthError`
8
- - [Minor BC] `TokenGenerator.generateToken` and `TokenGenerator.generateToken` might return a `Response` instead of a plain object. This should not break anything as the response is handled by the `TokenStorage` unless you call directly the `TokenGenerator` (which you should not). Returning an object has been deprecated and is only used in the `ProvidedTokenGenerator` (which is also deprecated)
9
- - [Minor BC] `OauthError.previousError` might be undefined
10
- - [Deprecation] Deprecate `ProvidedTokenGenerator`. You should use one of the oauth2 generator or implement your own custom generator.
11
- - [Deprecation] Calling `AbstractTokenGenerator._manageOauthError` is deprecated. You should return the `Response` instead :
12
-
13
- ```diff
14
- generateToken() {
15
- const body = // … generate body
16
-
17
- return fetch(url, {
18
- method: 'POST',
19
- body,
20
- + });
21
- - }).then((response) => {
22
- - if (response.status < 400) {
23
- - return response;
24
- - }
25
-
26
- - return this._manageOauthError(response);
27
- - });
28
- }
29
- ```
30
-
31
- ## 6.5.2
32
-
33
- Fix regression from `6.5.1` : `TokenStorage.refreshToken` does now throws an Error anymore if there is no token stored in the storage.
34
-
35
- ## 6.5.1
36
-
37
- - getItem from AsyncStorage interface might return null
38
- - `TokenStorage.refreshToken` now throws an Error if there is no token stored in the storage.
39
-
40
- ## 6.5.0
41
-
42
- ### Added
43
-
44
- Accept Relation.ONE_TO_ONE relation.
45
- It is basically handled the same way as MANY_TO_ONE, but has been added for semantic purpose.
46
- The comportment may differ later.
47
-
48
- ## 6.4.1
49
-
50
- ### Fixed
51
-
52
- - withUnitOfWork returns a clone of the base repository to avoid race condition on `isUnitOfWorkEnabled`
53
-
54
- ## 6.4.0
55
-
56
- - allow unitOfWork deactivation on find\* calls
57
-
58
- ## 6.3.0
59
-
60
- ### Added
61
-
62
- Accept Relation.MANY_TO_MANY relation.
63
- It is basically handled the same way as ONE_TO_MANY, but has been added for semantic purpose.
64
- The comportment may differ later.
65
-
66
- ## 6.2.0
67
-
68
- ### Changed
69
-
70
- - [TypeScript] better handle deserializeResponse method definition
71
-
72
- ## 6.1.0
73
-
74
- ### Added
75
-
76
- Export `MetadataDefinition` for AbstractClient inheritance
77
-
78
- ## 6.0.0
79
-
80
- ### Changed
81
-
82
- - [BREAKING] UnitOfWork is disabled by default, one must add a prop `unitOfWorkEnabled` with value true to the config object passed to the RestClientSdk's constructor in order to enable it
83
- - TokenStorage's `generateToken` and `refreshToken` methods are now memoized in order to avoid bugs when making concurrent calls
84
-
85
- ## 5.0.0
86
-
87
- This release is a migration to TypeScript, but the API stay the same. The only breaking changes are more fixed bugs that might be breaking in really improbable case.
88
-
89
- ### Changed
90
-
91
- - [BREAKING] TokenGenerator's `refreshToken` method signature changed from `refreshToken(accessToken, parameters)` to `refreshToken(accessToken)`.
92
- If you did extend the `AbstractToken` generator, you shouldn't relly on the second parameter.
93
- As a matter of fact, the auto-refreshed token in `AbstractClient` did not send any parameters either, so it should not have been working before !
94
- Accordingly The `refreshToken` method of `TokenStorage` signature changed from `refreshToken(parameters)` to `refreshToken()`
95
- - [Might Break] all pseudo-private methods and attributes (starting with `_`) are unavailable and are now really private (or protected).
96
- - `_storeAccessToken` should be replace by a `ProvidedTokenGenerator`
97
- - [Might Break] `ClassMetadata`, `Attribute` and `Relation` attributes are now `readonly`. You can not change them after initialization.
98
- - [Might Break] `AbstractTokenGenerator` is now abstract. It should not have been used directly anyway. It implies that the method that previously did thrown errors are not callable (`generateToken`, `refreshToken` and `checkTokenGeneratorConfig`). They should not have been called. They don't exist in JS land anymore.
99
- - [Might Break] `canAutogenerateToken` has been removed from the token storages and replaced by a `autogenerateToken()` method (it's not real POO, but I did not manage to deal with instance of for now)
100
- - [Might Break] AbstractClient.\_refreshTokenAndRefetch does not take the response as a first argument (it wan unused). The method was supposed to be private be the way.
101
-
102
- - Make `SerializerInterace` and `Serializer` input and output understandable
103
-
104
- ### Added
105
-
106
- - export (and implement) `RestClientSdkInterface` and `TokenStorageInterface`
107
- - export `TokenGeneratorInterface` and `AsyncStorageInterface`
108
-
109
- ## 4.1.4
110
-
111
- ### Changed
112
-
113
- - Passing a string as argument to `ProvidedTokenGenerator` is now deprecated. You should pass the token object instead. It should have had a weird comportment before by the way.
114
-
115
- ### Fixed
116
-
117
- - Fix issue when two token generation are send on the same time : the second one will not throw an error now.
118
-
119
- ## 4.1.3
120
-
121
- ### Fixed
122
-
123
- - Fix issue when no token is provided but the object is `{ expires_at: null }`
124
-
125
- ## 4.1.2
126
-
127
- ### Fixed
128
-
129
- - Fix issue with urijs 1.19.2
130
-
131
- ## 4.1.1
132
-
133
- ### Changed
134
-
135
- - replace object spread with Object.assign for build to work
136
-
137
- ## 4.1.0
138
-
139
- ### Changed
140
-
141
- - main AbstractClient CRUD methods accept additional requestParams for overriding fetch params like method, headers, etc.
142
-
143
- ## 4.0.1
144
-
145
- ### Changed
146
-
147
- - downgraded jest and babel-jest to ^23.6.0 in order to fix tests
148
-
149
- ## 4.0.0
150
-
151
- ### Changed
152
-
153
- - Do not generate token expires_at in \_storeAccessToken since it is sometimes used from outside, in tests for instance (even though it is supposed to be private)
154
- - [Breaking] throw new error types when oauth calls fail, they all wrap the originalError => InvalidGrantError, InvalidScopeError which both extend OauthError. Original error can be found at error.previousError. If it was an HttpError the response is at error.previousError.baseResponse
155
-
156
- ## 3.2.1
157
-
158
- ### Changed
159
-
160
- - Refactor error handling with error factory and handle 400's in refreshToken of PasswordGenerator
161
-
162
- ## 3.2.0
163
-
164
- ### Changed
165
-
166
- - Pre-emptively refresh the access token if it is close to expiration before doing any request
167
-
168
- ## 3.1.1
169
-
170
- ### Changed
171
-
172
- - Read json response in \_manageUnauthorized when www-authenticate header is not available
173
-
174
- ## 3.1.0
175
-
176
- ### Changed
177
-
178
- - Store a new key `expires_at` in the access token (which is accessible with `TokenStorage.getAccessTokenObject`) to have the timestamp after which the access token will be invalid, based on the `expires_in`
179
- - Add `TokenStorage.getCurrentTokenExpiresIn` function to known how many seconds are remaining for the access token currently stored
180
-
181
- ## 3.0.0
182
-
183
- ### Changed
184
-
185
- - [Breaking] `AccessDeniedError` is now `UnauthorizedError`
186
- - [Breaking] Default error is now `HttpError`
187
- - Add `ConflictError` to react to 409
188
-
189
- ## 2.3.0
190
-
191
- ### Changed
192
-
193
- - `TokenStorage` add possibility to pass access_token async storage key as constructor param
194
- - `AbstractClient._manageAccessDenied` checks headers instead of json to ensure refreshing the token is required
195
-
196
- ## 2.2.1
197
-
198
- ### Changed
199
-
200
- - `TokenStorage.getAccessTokenObject()` returns an object and null if the stored token is not an object
201
- - [Might Break] `TokenStorage.getAccessTokenObject()` does not return `undefined` anymore but `null` if no token object is found
202
-
203
- ## 2.2.0
204
-
205
- ### Changed
206
-
207
- - Add possibility to pass null as tokenStorage argument of the sdk
208
- - switch method names \_doFetch and \_fetchWithToken in AbstractClient for coherence
209
-
210
- ## 2.1.0
211
-
212
- ### Changed
213
-
214
- - Add method getAccessTokenObject to TokenStorage
215
-
216
- ## 2.0.1
217
-
218
- ### Changed
219
-
220
- - Better packaging system [#48](https://github.com/mapado/rest-client-js-sdk/pull/48)
221
-
222
- ## 2.0.0
223
-
224
- ### Added
225
-
226
- - [Might break] Custom serializer can:
227
- - `serializeItem` has been splitted into `normalizeItem` + `encodeItem`
228
- - `deserializeItem` has been splitted into `denormalizeItem` + `decodeItem`
229
- - `deserializeList` has been splitted into `denormalizeList` + `decodeList`
230
-
231
- You must implement them if you have a custom serialization that do not use plain javascript objects.
232
-
233
- ### Changed
234
-
235
- - [Breaking] Calling `restClientSdk.foo.xxx` is deprecated, you must now call `restClientSdk.getRepository('foo').xxx`
236
- - [Breaking] RestClientSdk now takes a Mapping instance instead of a clientList. This instance is required
237
- - [Breaking] `getName` has been removed and replaced by the classmetadata key. Its return was previously sent to the serializer, it's now the mapping that is sent now.
238
- Beware that now, the `key` is now used both to call the repository name, and passed to the serializer
239
- Before:
240
-
241
- ```js
242
- class SomeClient extends AbstractClient {
243
- getName() {
244
- return 'SomeClient';
245
- }
246
- }
247
-
248
- new RestClientSdk(
249
- // ...
250
- {
251
- foo: SomeClient,
252
- }
253
- );
254
- ```
255
-
256
- Now:
257
-
258
- ```js
259
- const metadata = new ClassMetadata('foo', 'some_endpoint');
260
- mapping = new Mapping();
261
- mapping.setMapping([ metadata ]);
262
-
263
- const sdk = new RestClientSdk(/* ... */, mapping); // `foo` will be used in serializer too
264
- sdk.foo.find();
265
- ```
266
-
267
- - [Breaking] Custom Serializer: If you had a Collection entity containing the result of you entities, you will need to implement the [iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) on this object, this way, we can register all entities in the unit of work.
268
-
269
- ### Removed
270
-
271
- - Dropped support for node 6
272
- - AbstractClient does not need to specify `getPathBase` anymore: this is generated via the classmetata. You can still override it.
273
- - `getEntityURI` is not mandatory anymore. it will be autogenerate by the AbstractClient. You can still override it
274
- - There is no need to create an empty client extending `AbstractClient` now, the default will be `AbstractClient`
275
- - config `prefix` is not used anymore, you should specify your prefix in the mapping: `new Mapping('/v1')`
276
-
277
- ## 2.0.0-rc.14
278
-
279
- Check relations in `isValidMapping`
280
-
281
- ## 2.0.0-rc.13
282
-
283
- Fix issue when setting a ManyToOne relatossue when setting a ManyToOne relation to `null`n to `null`
284
-
285
- ## 2.0.0-rc.12
286
-
287
- add a function to test mapping validity
288
-
289
- ## 2.0.0-rc.10 + 2.0.0-rc.11
290
-
291
- deserialize + normalize item in unitofwork
292
-
293
- ## 2.0.0-rc.9
294
-
295
- creating or updating an "complex" entity (not a basic JS object) would throw an error
296
-
297
- ## 2.0.0-rc.8
298
-
299
- remove `async` method (that already returned a Promise object)
300
-
301
- ## 2.0.0-rc.7
302
-
303
- Fix issue when posting a ManyToOne relation with only the id as string
304
-
305
- ## 2.0.0-rc.6
306
-
307
- Fix bug in delete call (not returning the response)
308
-
309
- ## 2.0.0-rc.5
310
-
311
- Fix bug in serializer
312
-
313
- ## 2.0.0-rc.4
314
-
315
- Fix issue with list denormalized oo objects
316
-
317
- ## 2.0.0-rc.3
318
-
319
- Cleaner relations, matches the Arguments attributes
320
-
321
- ## 2.0.0-rc.2
322
-
323
- ### Changed
324
-
325
- - `ONE_TO_MANY` and `MANY_TO_ONE` constant are now exported via the `Relation.ONE_TO_MANY` and `Relation.MANY_TO_ONE`, not in the main package
326
-
327
- ## 2.0.0-rc.1
328
-
329
- See release note for 2.0.0
330
-
331
- ## [1.3.2] - 2017-12-04
332
-
333
- ### Changed
334
-
335
- - fix simultaneous refresh token throwing error when trying to access to
336
- response body twice
337
-
338
- ## [1.3.1] - 2017-12-04
339
-
340
- ### Changed
341
-
342
- - add error message to AccessDeniedError in PasswordGenerator's refreshToken
343
-
344
- ## [1.3.0] - 2017-11-29
345
-
346
- ### Changed
347
-
348
- - throw AccessDeniedError only on BadRequestError in PasswordGenerator
349
- refreshToken
350
-
351
- ## [1.2.0] - 2017-11-10
352
-
353
- ### Changed
354
-
355
- - fix response passed as error message in Errors
356
- - throw AccessDeniedError on any Error in PasswordGenerator refreshToken
357
- - allow to pass scope param in tokenGeneratorConfig
358
-
359
- ## [1.1.1] - 2017-10-08
360
-
361
- ### Changed
362
-
363
- - upgrade rollup to 0.50.0
364
-
365
- ## [1.1.0] - 2017-08-30
366
-
367
- ### Changed
368
-
369
- - Pass on response to serializer
370
- - Upgrade dependencies (rollup 0.49, eslint 4, etc.)
371
- - Add prettier to project
372
-
373
- ## [1.0.5] - 2017-08-30
374
-
375
- ### Changed
376
-
377
- - Fix token loop when token is not valid anymore
378
-
379
- ## [1.0.4] - 2017-07-28
380
-
381
- ### Changed
382
-
383
- - Remove undefined headers
384
-
385
- ## [1.0.3] - 2017-07-27
386
-
387
- ### Changed
388
-
389
- - Allow overriding base headers
390
- [#24](https://github.com/mapado/rest-client-js-sdk/pull/24)
391
-
392
- ## [1.0.2] - 2017-07-04
393
-
394
- This release is the same as 0.15.0 and though fully compatible
395
-
396
- ### Changed
397
-
398
- - Rolled back to urijs because domurl use the default node implementation which
399
- is not compatible with the stack we use. The real future solution will be to
400
- use Javascript `URL` object but too early and unstable for now
401
-
402
- ## [1.0.1] - 2017-07-03 - [YANKED]
403
-
404
- ### Changed
405
-
406
- - Make urijs implementation work again but might be breaking
407
- - Url constructor passed with `noTransform = true` for better perf and avoid
408
- potential bugs
409
-
410
- ## [1.0.0] - 2017-07-03 - [YANKED]
411
-
412
- ### Changed
413
-
414
- - Replace [urijs](https://medialize.github.io/URI.js/) dependency by smaller
415
- [domurl](https://github.com/Mikhus/domurl)
416
-
417
- ## [0.15.0] - 2017-06-27
418
-
419
- ### Added
420
-
421
- - Added the current URI as referer for http calls
422
-
423
- ## [0.14.x]
424
-
425
- ### breaking changes
426
-
427
- Error responses in PasswordGenerator and ClientCredentialsGenerator now throw
428
- proper js errors instead of returning the response in the promise rejection
429
-
430
- ## [0.13.x]
431
-
432
- ### breaking changes
433
-
434
- The library does not depends on `immutablejs` anymore, so we needed to make a
435
- few breaking changes:
436
-
437
- - Do not depend on `@id` anymore: The `AbstractClient` need to implements a
438
- `getEntityURI(entity)` and return an query string from it. This is not a great
439
- pattern, but it will do for now.
440
- (https://github.com/mapado/rest-client-js-sdk/pull/19)
441
- - The `entityFactory` does not exists anymore. It has been replaced by a
442
- `Serializer`: (https://github.com/mapado/rest-client-js-sdk/pull/21)
443
- - If you used the default entityFactory, you will now receive plain Javascript
444
- objects instead of immutable's Map or List
445
- - If you previously overrided the `entityFactory`, you will need to switch to
446
- the new `Serializer` object: It is much more extensible but is a bit more
447
- complex to extend. See README to know how to do it.
448
- - the `createEntityFromJsonResponse` method has been renamed to
449
- `deserializeResponse`
450
- - The library moved from ES5 to bundling with rollupjs, that should not break
451
- anything and should improve size of bundle but I am not so sure of this, so
452
- patch may follow (https://github.com/mapado/rest-client-js-sdk/pull/20)
453
-
454
- ## [0.12.x]
455
-
456
- ### breaking changes
457
-
458
- - a `delete` does not call `createEntityFromJsonResponse` anymore as it should
459
- return a "204 No Content" or a "404 Not Found"
460
-
461
- ## [0.11.x]
462
-
463
- ### breaking changes
464
-
465
- - `ProviderTokenGenerator` does not accept a param object anymore on its second
466
- argument.
467
-
468
- ### new features
469
-
470
- - `ProviderTokenGenerator` now accept a function on its second argument which
471
- will be called on `refreshToken`, so you can fully customize the behavior. The
472
- function must return a Promise.
473
-
474
- ## [0.9.x]
475
-
476
- ### breaking changes
477
-
478
- - if the response status is 4xx or 5xx: an error is thrown
479
- [#13](https://github.com/mapado/rest-client-js-sdk/pull/13)
480
-
481
- ### new features
482
-
483
- - memoize token generation and refresh
484
- [#12](https://github.com/mapado/rest-client-js-sdk/pull/12)
485
-
486
- ## [0.6.x]
487
-
488
- ### breaking changes
489
-
490
- The `queryParam` argument was added where needed in the AbstractClient class:
491
-
492
- - `findAll(queryParam = {}, pathParameters = {})`
493
- - `create(entity, queryParam = {}, pathParameters = {})`
494
-
495
- ### new features
496
-
497
- The `queryParam` argument was added where needed in the AbstractClient class:
498
-
499
- - `update(entity, queryParam = {})`