@amedia/user 0.14.2 → 0.14.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.
package/README.md CHANGED
@@ -1,27 +1,17 @@
1
1
  # @amedia/user
2
+ The goal of this module is to simplify the usage of aID data and services in Amedia frontend code. The module is designed to be used several places on a webpage independently, and the module will ensure that requests from different parts of the webpage are handled in an efficient manner.
2
3
 
3
- The goal of this module is to simplify the usage of aID data and services in Amedia frontend code. The module is
4
- designed to be used several places on a webpage independently, and the module will ensure that requests from
5
- different parts of the webpage are handled in an efficient manner.
6
-
7
- An important requirement for this module is Eik. When used in production, this module should always be loaded from
8
- an alias in Eik. This is to ensure that all components on a page that uses this module will use same version. The
9
- normal way to load the module from Eik is through import maps.
4
+ An important requirement for this module is Eik. When used in production, this module should always be loaded from an alias in Eik. This is to ensure that all components on a page that uses this module will use same version. The normal way to load the module from Eik is through import maps.
10
5
 
11
6
  # Usage
12
-
13
7
  Please be advised that you are required to use ESM in order to use this module.
14
8
 
15
- ## Importing the module
16
-
17
- Add this module to your project by running `npm install -d @amedia/user`. This will allow for type-hinting, but will not include any code.
18
- This means you must also set up import maps for loading the actual code. Just point `@amedia/user` to
19
- `https://assets.acdn.no/pkg/@amedia/user/v0/user.js`.
9
+ ## Importing the module
10
+ Add this module to your project by running `npm install -d @amedia/user`. This will allow for type-hinting, but will not include any code. This means you must also set up import maps for loading the actual code. Just point `@amedia/user` to `https://assets.acdn.no/pkg/@amedia/user/v0/user.js`.
20
11
 
21
12
  See Ego, Bacchus or Saturn for examples on how to use this module through Eik.
22
13
 
23
14
  Once the module is installed, it can be imported in your source code using a standard import like this:
24
-
25
15
  ```ts
26
16
  import {
27
17
  UserDataRequest,
@@ -32,15 +22,11 @@ import {
32
22
  } from '@amedia/user';
33
23
  ```
34
24
 
35
- When your source code is bundled together for production, it's important that the bundler (rollup, webpack etc.) will
36
- use an import map to replace this import with `import {} from https://assets.acdn.no/pkg/@amedia/user/v0/user.js` instead
37
- of bundling a hard coded version of the module in your bundled assets. If this happens, the page will end up with
38
- different versions of this module, which in time will cause incompatibilities and extra code to download.
25
+ When your source code is bundled together for production, it's important that the bundler (rollup, webpack etc.) will use an import map to replace this import with `import {} from https://assets.acdn.no/pkg/@amedia/user/v0/user.js` instead of bundling a hard coded version of the module in your bundled assets. If this happens, the page will end up with different versions of this module, which in time will cause incompatibilities and extra code to download.
39
26
 
40
27
  You can read more about Eik on [Slite](https://amedia.slite.com/app/channels/hOlqx3Miez/notes/iexhL4MZn3).
41
28
 
42
29
  ## Contributing to @amedia/user
43
-
44
30
  Hey, thanks! :)
45
31
 
46
32
  It's often nice to do development while testing on a real app. You may do so using `npm link`. When you run then `npm run build` this will expose actual code, letting you develop faster. This is because we still export user.js from the package, but replaces it content with an error if used directly.
@@ -48,21 +34,15 @@ It's often nice to do development while testing on a real app. You may do so usi
48
34
  PS: Remember to comment-out the module in import maps ;-)
49
35
 
50
36
  ## Getting user data
37
+ The most common use case for aID on newspapers is to get some kind of data about a user, this could be the user's name, some stored preference, access or data that has been derived about the user.
51
38
 
52
- The most common use case for aID on newspapers is to get some kind of data about a user, this could be the user's name,
53
- some stored preference, access or data that has been derived about the user.
39
+ To get user data you first need to create a `UserDataRequest`, then you specify what data you need and once that is done, you decide if you want to wait until all data is available, or you want to get partial updates.
54
40
 
55
- To get user data you first need to create a `UserDataRequest`, then you specify what data you need and once that is
56
- done, you decide if you want to wait until all data is available, or you want to get partial updates.
57
-
58
- This module tries to simplify the model representing various data about the user. We have introduced (and re used) some
59
- concepts that are listed here.
41
+ This module tries to simplify the model representing various data about the user. We have introduced (and re used) some concepts that are listed here.
60
42
 
61
43
  ### Data model
62
44
  #### Attributes
63
-
64
45
  Attributes are data directly related to the user, with the exception of access. Supported attributes are:
65
-
66
46
  - uuid (string): The user's unique ID
67
47
  - name (string): User's full name
68
48
  - trackingKey (string): Unique ID of user that can be used for tracking (pseudonym)
@@ -72,11 +52,9 @@ Attributes are data directly related to the user, with the exception of access.
72
52
 
73
53
  Attributes are requested by calling `.withAttributes()` on a `UserDataRequest` with a list of the attributes you need.
74
54
 
75
- In the response, `attributes` is an object where each requested attribute is an attribute. So you can get the name by
76
- accessing `attributes.name` for example.
55
+ In the response, `attributes` is an object where each requested attribute is an attribute. So you can get the name by accessing `attributes.name` for example.
77
56
 
78
57
  Privacy preferences contains the following boolean attributes:
79
-
80
58
  - allowResearchUsage
81
59
  - connectWithSurveys
82
60
  - personalizedAds
@@ -85,43 +63,28 @@ Privacy preferences contains the following boolean attributes:
85
63
  NOTE: Fetching each attribute has a cost, so keep the list to a minimum. Don't request attributes you don't really need.
86
64
 
87
65
  #### Storage
88
-
89
- Storage are namespaces stored in Europa. A namespace is a named set of key value pairs stored for a specific user.
90
- An example could be favourite_teams, which could contain team_id as key and timestamp it was stored as favourite as value.
66
+ Storage are namespaces stored in Europa. A namespace is a named set of key value pairs stored for a specific user. An example could be favourite_teams, which could contain team_id as key and timestamp it was stored as favourite as value.
91
67
 
92
68
  Storage is requested by calling `.withStorage()` on a `UserDataRequest` with a list of namespaces you need.
93
69
 
94
- In the response, `storage` is an object with each namespace as an attribute which leads to an object with attributes
95
- for each key in the namespace. So you can access `storage.favourite_teams.myteamid` and get the value stored for
96
- `teamid` in the `favourite_teams` namespace. This value will be whatever was saved there.
70
+ In the response, `storage` is an object with each namespace as an attribute which leads to an object with attributes for each key in the namespace. So you can access `storage.favourite_teams.myteamid` and get the value stored for `teamid` in the `favourite_teams` namespace. This value will be whatever was saved there.
97
71
 
98
72
  #### State
99
-
100
- State is meant to describe the current context the user is in right now. It's not directly requested, but will always
101
- be a part of the response.
73
+ State is meant to describe the current context the user is in right now. It's not directly requested, but will always be a part of the response.
102
74
 
103
75
  Current attributes in `state`:
104
76
  - isLoggedIn (boolean): Is the user currently logged in? If not, most attributes will be undefined
105
77
  - emergencyMode (list of strings): Current state of emergency mode in production environment (paywall, aid etc.)
106
78
 
107
79
  ### Executing the request
80
+ Once you have created a request and specified the data you need, the final step is to decide how you want to get the data once it's available. You can either choose to subscribe to updates or wait until everything is ready and get everything in one package.
108
81
 
109
- Once you have created a request and specified the data you need, the final step is to decide how you want to get
110
- the data once it's available. You can either choose to subscribe to updates or wait until everything is ready and get
111
- everything in one package.
112
-
113
- The response to the request will be an object with attributes for state, attributes and storage. In the
114
- examples below these are unpacked for easier access.
82
+ The response to the request will be an object with attributes for state, attributes and storage. In the examples below these are unpacked for easier access.
115
83
 
116
84
  #### Subscribing to updates
117
-
118
- The most flexible way to get userdata is by subscribing to updates. This is done by calling `.subscribe()` on the
119
- `UserDataRequest` with a callback function that can handle the updates once they arrive. This is especially useful
120
- when the time it can take to get the data can vary. Getting the user's name is very fast, so you can display the
121
- user's name before you have received storage for example.
85
+ The most flexible way to get userdata is by subscribing to updates. This is done by calling `.subscribe()` on the `UserDataRequest` with a callback function that can handle the updates once they arrive. This is especially useful when the time it can take to get the data can vary. Getting the user's name is very fast, so you can display the user's name before you have received storage for example.
122
86
 
123
87
  Full usage example:
124
-
125
88
  ```ts
126
89
  import { UserDataRequest } from '...';
127
90
 
@@ -133,20 +96,14 @@ new UserDataRequest()
133
96
  });
134
97
  ```
135
98
 
136
- The callback you supplied to subscribe is called whenever there are any changes to the properties
137
- you have requested, so be prepared to rerender.
99
+ The callback you supplied to subscribe is called whenever there are any changes to the properties you have requested, so be prepared to rerender.
138
100
 
139
- Also, your requested properties might not arrive all at once. This callback will be called whenever
140
- we get data in from the various services.
101
+ Also, your requested properties might not arrive all at once. This callback will be called whenever we get data in from the various services.
141
102
 
142
103
  #### Fetching all the data once (no rerenders)
143
-
144
- In many use cases it's more convenient to just wait until everything is ready so you don't have to handle
145
- multiple callbacks. In these cases it's easier to call `.fetch()`. This method will return a `Promise` that
146
- resolves the same object you would get in the `subscribe` callback.
104
+ In many use cases it's more convenient to just wait until everything is ready so you don't have to handle multiple callbacks. In these cases it's easier to call `.fetch()`. This method will return a `Promise` that resolves the same object you would get in the `subscribe` callback.
147
105
 
148
106
  Full usage example:
149
-
150
107
  ```ts
151
108
  import { UserDataRequest } from '...';
152
109
 
@@ -159,21 +116,14 @@ new UserDataRequest()
159
116
  });
160
117
  ```
161
118
 
162
- Fetch will wait until it has all the data you requested before resolving, unless the user is not currently
163
- logged in. Internally `.fetch()` will use `.subscribe()` and just wait until everything is ready before
164
- resolving the returned prommise.
119
+ Fetch will wait until it has all the data you requested before resolving, unless the user is not currently logged in. Internally `.fetch()` will use `.subscribe()` and just wait until everything is ready before resolving the returned promise.
165
120
 
166
- If you really need to render the user's name etc. as fast as possible, use `.subscribe()`, if not,
167
- this is probably easier.
121
+ If you really need to render the user's name etc. as fast as possible, use `.subscribe()`, if not, this is probably easier.
168
122
 
169
123
  ##### Timeouts
170
-
171
- Especially poor connections may result in almost eternal wait times - which is no good if your app is locked while
172
- waiting on the data. Because of this we have introduced a timeout. A timeout will cause the fetch to reject with
173
- FetchTimeoutError.
124
+ Especially poor connections may result in almost eternal wait times - which is no good if your app is locked while waiting on the data. Because of this we have introduced a timeout. A timeout will cause the fetch to reject with FetchTimeoutError.
174
125
 
175
126
  FetchTimeoutError will include any data we might have gotten before we timed out
176
-
177
127
  ```ts
178
128
  .catch((e) => {
179
129
  if (e instanceof FetchTimeoutError) {
@@ -183,58 +133,35 @@ FetchTimeoutError will include any data we might have gotten before we timed out
183
133
  }
184
134
  ```
185
135
 
186
- If you're running a background task and don't mind waiting longer than default (10 seconds), you may set a longer
187
- timeout in fetch:
188
-
136
+ If you're running a background task and don't mind waiting longer than default (10 seconds), you may set a longer timeout in fetch:
189
137
  ```ts
190
138
  .fetch({timeout: 60000 /* milliseconds */ })
191
139
  ```
192
140
 
193
141
  ## Unlocking the paywall
142
+ Amedia's publications use a Paywall that's based on a cookie called VSTOKEN that is read by Varnish and used by the content system to decide if the content should be shown to the user or not. If not, the content will load what we call an incentive, a dialogue above the content, that will allow the user to log in and buy subscriptions. The incentive will use a `PaywallUnlockRequest` to see if it can somehow grant access to the user. In some cases it makes sense to create a different user interface for a paywall. In these cases we recommend that you use this `PaywallUnlockRequest` in order to get the same functionality.
194
143
 
195
- Amedia's publications use a Paywall that's based on a cookie called VSTOKEN that is read by Varnish and used by
196
- the content system to decide if the content should be shown to the user or not. If not, the content will load what
197
- we call an incentive, a dialogue above the content, that will allow the user to log in and buy subscriptions. The
198
- incentive will use a `PaywallUnlockRequest` to see if it can somehow grant access to the user. In some cases it makes
199
- sense to create a different user interface for a paywall. In these cases we recommend that you use this
200
- `PaywallUnlockRequest` in order to get the same functionality.
201
-
202
- More information about the paywall can be found here:
203
- [How the Paywall works](https://amedia.slite.com/app/channels/hOlqx3Miez/notes/UFqOFRV3g1)
204
-
205
- Information about the incentive can also be useful, since you probably need to replicate this functionality if you
206
- create a new user interface:
207
- [How the Incentive works](https://amedia.slite.com/app/channels/hOlqx3Miez/notes/SroHksU9u)
144
+ More information about the paywall can be found here: [How the Paywall works](https://amedia.slite.com/app/channels/hOlqx3Miez/notes/UFqOFRV3g1)
208
145
 
209
- To unlock the paywall, you first need to create a new `PaywallUnlockRequest`. Once created, you can set some options by
210
- calling methods on this request:
146
+ Information about the incentive can also be useful, since you probably need to replicate this functionality if you create a new user interface: [How the Incentive works](https://amedia.slite.com/app/channels/hOlqx3Miez/notes/SroHksU9u)
211
147
 
148
+ To unlock the paywall, you first need to create a new `PaywallUnlockRequest`. Once created, you can set some options by calling methods on this request:
212
149
  - `reloadOnAccess()`: If the paywall unlocker finds sufficient access for the user it will reload the current page
213
150
  - `redirectOnAccess(requestedUrl: string)`: If the paywall unlocker finds sufficient access for the user, it will send the user
214
151
  to `requestedUrl`. (Provides more flexibility than `reloadOnAccess()`)
215
152
  - `withAccessFeatures(accessFeatures: string[])`: Specify what access features will give access to the current content.
216
153
  The default is [`newspaper`].
217
154
 
218
- More details about the access model can be found here:
219
- [Access model](https://amedia.slite.com/app/channels/hOlqx3Miez/notes/nhG2Ok39BN)
155
+ More details about the access model can be found here: [Access model](https://amedia.slite.com/app/channels/hOlqx3Miez/notes/nhG2Ok39BN)
220
156
 
221
- Once your options have been set up, you can call `tryUnlock()`. This is when all the magic happens. The unlocker will
222
- try to auto login the user on the current domain, check access, activate subscriptions in the subscription system,
223
- check for stuff like IP based access etc. When this is done, it will resolve the `Promise` that was returned by
224
- `tryUnlock()`.
157
+ Once your options have been set up, you can call `tryUnlock()`. This is when all the magic happens. The unlocker will try to auto login the user on the current domain, check access, activate subscriptions in the subscription system, check for stuff like IP based access etc. When this is done, it will resolve the `Promise` that was returned by `tryUnlock()`.
225
158
 
226
- The resolution to the promise contains an object with attributes you can use to get details about why the user did
227
- not get access (or if he had access if you don't opt for reload or redirect). The object contains the following:
228
-
229
- - isLoggedIn: True if the user is logged in, false otherwise. Useful if you want to show a login button, which makes
230
- no sense for logged in users.
159
+ The resolution to the promise contains an object with attributes you can use to get details about why the user did not get access (or if he had access if you don't opt for reload or redirect). The object contains the following:
160
+ - isLoggedIn: True if the user is logged in, false otherwise. Useful if you want to show a login button, which makes no sense for logged in users.
231
161
  - hasAccess: True if the user has access. Always false if you called `reloadOnAccess()` or `redirectOnAccess()`.
232
- - accessFeatures: List of access features the user has access to. Empty list if user is logged out or has no access.
233
- This list is useful if you want to upgrade from 'newspaper' to 'plussalt' for instance. You might want to give
234
- a different user experience to users with some access than users with no access.
162
+ - accessFeatures: List of access features the user has access to. Empty list if user is logged out or has no access. This list is useful if you want to upgrade from 'newspaper' to 'plussalt' for instance. You might want to give a different user experience to users with some access than users with no access.
235
163
 
236
164
  Full usage example:
237
-
238
165
  ```ts
239
166
  import { PaywallUnlockRequest } from '...';
240
167
 
@@ -270,41 +197,26 @@ new PaywallUnlockRequest()
270
197
  });
271
198
  ```
272
199
 
273
- Note that this *might result in redirects/reloads* if the user is not already logged in.
274
- In that case you will end up here again if logging in did not result in access.
200
+ Note that this *might result in redirects/reloads* if the user is not already logged in. In that case you will end up here again if logging in did not result in access.
275
201
 
276
202
  ## Actions
277
-
278
203
  The following methods are actions that the user needs to be able to perform in an environment using logged in users.
279
204
 
280
205
  ### `goToLoginPage(requestedUrl: string)`
206
+ This action will send the user to the aID login page. It will take care of building the correct URL, including your current publication domain, so the login page is skinned correctly.
281
207
 
282
- This action will send the user to the aID login page. It will take care of building the correct URL, including
283
- your current publication domain, so the login page is skinned correctly.
284
-
285
- You may include a requestedUrl if you need to control where the user should end up after logging in. The default
286
- is to send the user back to the current URL where this action was called.
208
+ You may include a requestedUrl if you need to control where the user should end up after logging in. The default is to send the user back to the current URL where this action was called.
287
209
 
288
210
  ### `logout()`
289
-
290
- This action will log the user out of aID. The logout is global, meaning it will log the session out of all
291
- publications and aid.no.
211
+ This action will log the user out of aID. The logout is global, meaning it will log the session out of all publications and aid.no.
292
212
 
293
213
  ## Updating storage
294
-
295
- If you need to store preferences, favourite teams etc for the user, you can choose between two methods. One will
296
- update only the attributes of a namespace that you specify, the other will update everything. The main difference is
297
- that if you opt for updating everything, attributes that are present on the backend, but not in the update, will be
298
- deleted.
214
+ If you need to store preferences, favourite teams etc for the user, you can choose between two methods. One will update only the attributes of a namespace that you specify, the other will update everything. The main difference is that if you opt for updating everything, attributes that are present on the backend, but not in the update, will be deleted.
299
215
 
300
216
  ### Update changed values (PATCH)
301
-
302
- The safest way to update a value is to use `updateStorage()`. This will send a `PATCH` to Europa to only update
303
- the specified attributes of a namespace, and keep the rest as it is. This reduces concurrency issues where someone could
304
- have updated a different attribute after you read the namespace.
217
+ The safest way to update a value is to use `updateStorage()`. This will send a `PATCH` to Europa to only update the specified attributes of a namespace, and keep the rest as it is. This reduces concurrency issues where someone could have updated a different attribute after you read the namespace.
305
218
 
306
219
  Example of use:
307
-
308
220
  ```ts
309
221
  import { updateStorage } from '...';
310
222
 
@@ -315,19 +227,12 @@ updateStorage({
315
227
  });
316
228
  ```
317
229
 
318
- In the example, only `my` in `my_namespace` would be updated to `data`. If the namespace also contained
319
- `{ your: 'loss' }`, this would be kept untouched, so the resulting namespace would now contain
320
- `{ my: 'data', your: 'loss' }`.
230
+ In the example, only `my` in `my_namespace` would be updated to `data`. If the namespace also contained `{ your: 'loss' }`, this would be kept untouched, so the resulting namespace would now contain `{ my: 'data', your: 'loss' }`.
321
231
 
322
232
  ### Update the entire namespace (PUT)
323
-
324
- If you're not afraid of concurrency issues, or you need to make sure that old attributes are removed, you should
325
- use `saveStorage()`. This works in the same way as `updateStorage()`, but it will send a `PUT` to Europa, which will
326
- then make sure that attributes that are stored in the namespaces in the request, but are not a part of the request,
327
- will be removed.
233
+ If you're not afraid of concurrency issues, or you need to make sure that old attributes are removed, you should use `saveStorage()`. This works in the same way as `updateStorage()`, but it will send a `PUT` to Europa, which will then make sure that attributes that are stored in the namespaces in the request, but are not a part of the request, will be removed.
328
234
 
329
235
  Example of use:
330
-
331
236
  ```ts
332
237
  import { updateStorage } from '...';
333
238
 
@@ -338,49 +243,27 @@ saveStorage({
338
243
  });
339
244
  ```
340
245
 
341
- In the example, `my` in `my_namespace` would be updated to `data`. If the namespace also contained
342
- `{ your: 'loss' }`, this would removed, so the resulting namespace would now contain
343
- `{ my: 'data' }`.
246
+ In the example, `my` in `my_namespace` would be updated to `data`. If the namespace also contained `{ your: 'loss' }`, this would removed, so the resulting namespace would now contain `{ my: 'data' }`.
344
247
 
345
248
  ## Performance
346
- This app aims to be able to deliver a lot of data fast.
347
- Still, we might need to call several services in order
348
- to get what you need. We do try to cache whenever this
349
- makes sense, but please don't ask for data you don't need.
249
+ This app aims to be able to deliver a lot of data fast. Still, we might need to call several services in order to get what you need. We do try to cache whenever this makes sense, but please don't ask for data you don't need.
350
250
 
351
251
  # Behind the scenes
352
- There are a few techniques used to avoid overfetching and
353
- fetching multiple times when once would do.
252
+ There are a few techniques used to avoid overfetching and fetching multiple times when once would do.
354
253
 
355
254
  ## Event-based actions
356
- Much like
357
- [node-userdata-browser/userdata-client](https://github.com/amedia/node-userdata-browser)
358
- did, we utilize events to message that data is being
359
- requested. This allowed us to decouple your request from
360
- the particular instance that will serve it.
361
- This allows us to have this packed loaded by multiple
362
- different components across the page, and only process
363
- the requests one place.
364
- In addition, if the component that's currently processing
365
- requests should be unloaded for whatever reason, one
366
- of the other instances will automatically take over.
255
+ Much like [node-userdata-browser/userdata-client](https://github.com/amedia/node-userdata-browser) did, we utilize events to message that data is being requested. This allowed us to decouple your request from the particular instance that will serve it. This allows us to have this packed loaded by multiple different components across the page, and only process the requests one place. In addition, if the component that's currently processing requests should be unloaded for whatever reason, one of the other instances will automatically take over.
367
256
 
368
257
  ## Request de-duping
369
- Since we now process from a single instance of the package
370
- it's easy to avoid fetching the same resource multiple
371
- times.
258
+ Since we now process from a single instance of the package it's easy to avoid fetching the same resource multiple times.
372
259
 
373
260
  ## Caching
374
- Tha app has got few caching mechanisms, through local storage
375
- and indexeddb
261
+ Tha app has got few caching mechanisms, through local storage and indexeddb
376
262
 
377
263
  # Publishing new versions
378
-
379
- This module can be used both as an Eik module and as a standard NPM module. When publishing new versions, the version
380
- needs to be published to both channels.
264
+ This module can be used both as an Eik module and as a standard NPM module. When publishing new versions, the version needs to be published to both channels.
381
265
 
382
266
  ## NPM package
383
-
384
267
  To publish a new version to NPM, do the following:
385
268
 
386
269
  - Update version number in `package.json`
@@ -390,20 +273,15 @@ To publish a new version to NPM, do the following:
390
273
  Now the new version can be installed in a project by running `npm install -u @amedia/user@v<new version>`
391
274
 
392
275
  ## Eik
276
+ When publishing to Eik you need to take into consideration any breaking API changes. A new version can safely be published to Eik at any time, but when it is given an alias, any client using this alias will get the new version, so any breaking API changes will break all clients. If there are breaking changes a new alias must be created.
393
277
 
394
- When publishing to Eik you need to take into consideration any breaking API changes. A new version can safely be
395
- published to Eik at any time, but when it is given an alias, any client using this alias will get the new version,
396
- so any breaking API changes will break all clients. If there are breaking changes a new alias must be created.
397
-
398
- If for some reason we need to update clients using an older alias, we need to create a separate version where the API
399
- stays the same as the previous API in the same alias.
278
+ If for some reason we need to update clients using an older alias, we need to create a separate version where the API stays the same as the previous API in the same alias.
400
279
 
401
280
  The alias version should be the same as the major version of the NPM module.
402
281
 
403
282
  Before publishing to Eik, you need to be logged in by running `eik/eik-login` in the tools repo.
404
283
 
405
284
  To publish a new version do the following:
406
-
407
285
  - Update version number in `eik.json` to the same version as in `package.json`
408
286
  - Run `npm run eik:package` (no publishing will be done unless packages passes lint, typings, tests and builds successfully)
409
287
  - Run `npx eik package-alias @amedia/user <version from eik.json> <Alias version>`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.14.2",
3
+ "version": "0.14.3",
4
4
  "description": "Client lib for working with aID user and associated data",
5
5
  "repository": "https://github.com/amedia/amedia-user-js",
6
6
  "author": "Amedia Utvikling (ID og data)",
@@ -145,4 +145,31 @@ describe('Log', () => {
145
145
  contextError: expectRewrittenError('Downhill from here'),
146
146
  });
147
147
  });
148
+
149
+ describe('when logging fetch response', () => {
150
+ beforeEach(() => {
151
+ log.error(
152
+ 'Error log',
153
+ new Response('body says hi', {
154
+ headers: {
155
+ 'Cache-Control': 'no-store',
156
+ },
157
+ })
158
+ );
159
+ });
160
+
161
+ itShouldLogMessage('Error log');
162
+ itShouldLogContext({
163
+ response: {
164
+ body: 'body says hi',
165
+ headers: {
166
+ 'cache-control': 'no-store',
167
+ 'content-type': 'text/plain;charset=UTF-8',
168
+ },
169
+ status: 200,
170
+ statusText: 'OK',
171
+ url: '',
172
+ },
173
+ });
174
+ });
148
175
  });
package/src/utils/log.ts CHANGED
@@ -22,36 +22,28 @@ const rewriteErrorObject = (
22
22
  message: error.message,
23
23
  };
24
24
  Object.getOwnPropertyNames(error).forEach((key) => {
25
- // @ts-ignore
26
- rewrittenError[key] = error[key];
25
+ rewrittenError[key] = error[key as keyof typeof error];
27
26
  });
28
27
  return rewrittenError;
29
28
  };
30
29
 
31
30
  const rewriteResponseObject = async (
32
31
  response: Response
33
- ): Promise<
34
- { [key: string]: unknown } & {
35
- url: string;
36
- status: number;
37
- statusText: string;
38
- body: string;
39
- }
40
- > => {
32
+ ): Promise<Record<string, unknown>> => {
41
33
  const responseText = !response.bodyUsed
42
34
  ? await response.text()
43
35
  : 'Response body not available for logging';
44
- const rewrittenResponseObject: any = {
36
+ const headers: Record<string, string> = {};
37
+ response.headers.forEach((value, key) => {
38
+ headers[key] = value;
39
+ });
40
+ return {
45
41
  url: response.url,
46
42
  status: response.status,
47
43
  statusText: response.statusText,
44
+ headers,
48
45
  body: responseText,
49
46
  };
50
- Object.getOwnPropertyNames(response).forEach((key) => {
51
- // @ts-ignore
52
- rewrittenResponseObject[key] = response[key];
53
- });
54
- return rewrittenResponseObject;
55
47
  };
56
48
 
57
49
  function isError(param: any): param is Error {
@@ -66,39 +58,32 @@ const processIncomingLogData = async (
66
58
  message: string | Error,
67
59
  context: any = {}
68
60
  ): Promise<{ message: string; context: any }> => {
69
- let internalMessage = message;
70
- let internalContext = context || {};
71
- if (internalMessage instanceof Error) {
72
- const rewrittenErrorObject = rewriteErrorObject(internalMessage);
73
- internalMessage = rewrittenErrorObject.message;
74
- internalContext = { ...internalContext, error: rewrittenErrorObject };
61
+ const internalMessage: string =
62
+ typeof message === 'string' ? message : message.message;
63
+ const internalContext: Record<string, unknown> = {
64
+ origin: '@amedia/user',
65
+ };
66
+ if (message instanceof Error) {
67
+ internalContext.error = rewriteErrorObject(message);
75
68
  }
76
- internalContext = { ...internalContext, origin: '@amedia/user' };
69
+
77
70
  if (context instanceof Error) {
78
- const parsedContextError = rewriteErrorObject(context);
79
- internalContext = {
80
- ...internalContext,
81
- ...{
82
- [Object.keys(internalContext).includes('error')
83
- ? 'contextError'
84
- : 'error']: parsedContextError,
85
- },
86
- };
87
- } else if (internalContext instanceof Response) {
88
- const rewritten = await rewriteResponseObject(internalContext);
89
- internalContext = { ...internalContext, response: rewritten };
71
+ internalContext[
72
+ Object.keys(internalContext).includes('error') ? 'contextError' : 'error'
73
+ ] = rewriteErrorObject(context);
74
+ } else if (context instanceof Response) {
75
+ internalContext.response = await rewriteResponseObject(context);
90
76
  } else {
91
- // eslint-disable-next-line no-restricted-syntax
92
- for (const key of Object.keys(internalContext)) {
93
- const currentInternalContext = internalContext[key];
94
- if (isError(currentInternalContext)) {
95
- internalContext[key] = rewriteErrorObject(currentInternalContext);
96
- } else if (isResponse(currentInternalContext)) {
97
- // eslint-disable-next-line no-await-in-loop
98
- const rewritten = await rewriteResponseObject(currentInternalContext);
99
- internalContext[key] = rewritten;
77
+ Object.keys(context).forEach((key) => {
78
+ const currentContext = context[key];
79
+ if (isError(currentContext)) {
80
+ internalContext[key] = rewriteErrorObject(currentContext);
81
+ } else if (isResponse(currentContext)) {
82
+ internalContext[key] = rewriteResponseObject(currentContext);
83
+ } else {
84
+ internalContext[key] = currentContext;
100
85
  }
101
- }
86
+ });
102
87
  }
103
88
  return {
104
89
  message: internalMessage,