@amedia/user 0.7.2 → 0.7.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.
Files changed (93) hide show
  1. package/dist/index.d.ts +6 -17
  2. package/dist/index.js +7 -2
  3. package/dist/lib/authentication.d.ts +17 -0
  4. package/dist/lib/authentication.js +74 -0
  5. package/dist/lib/authorization.d.ts +14 -0
  6. package/dist/lib/authorization.js +51 -0
  7. package/dist/{cache/engines/indexeddb.d.ts → lib/cache/db.d.ts} +2 -3
  8. package/dist/lib/cache/db.js +13 -0
  9. package/dist/lib/cache/global.d.ts +9 -0
  10. package/dist/lib/cache/global.js +16 -0
  11. package/dist/lib/cache/types.d.ts +5 -0
  12. package/dist/lib/cache/types.js +2 -0
  13. package/dist/lib/queue.d.ts +5 -0
  14. package/dist/lib/queue.js +17 -0
  15. package/dist/lib/tools.d.ts +1 -0
  16. package/dist/lib/tools.js +2 -0
  17. package/dist/lib/user.d.ts +2 -0
  18. package/dist/lib/user.js +3 -0
  19. package/dist/services/cache.d.ts +9 -0
  20. package/dist/services/cache.js +34 -0
  21. package/dist/services/jupiter.d.ts +4 -4
  22. package/dist/services/jupiter.js +72 -0
  23. package/dist/services/pluto.d.ts +10 -6
  24. package/dist/services/pluto.js +40 -0
  25. package/package.json +1 -1
  26. package/src/actions/authorization.ts +2 -2
  27. package/src/actions/preferences.spec.ts +2 -14
  28. package/src/actions/preferences.ts +26 -54
  29. package/src/cache/index.spec.ts +2 -2
  30. package/src/clients/europa.spec.ts +51 -19
  31. package/src/clients/europa.ts +70 -53
  32. package/src/clients/jupiter.spec.ts +26 -0
  33. package/src/clients/jupiter.ts +3 -2
  34. package/src/clients/mercury.spec.ts +5 -7
  35. package/src/clients/mercury.ts +4 -2
  36. package/src/clients/pluto.spec.ts +0 -2
  37. package/src/eventHandlers/activation.ts +2 -2
  38. package/src/index-authentcation.spec.ts +2 -1
  39. package/src/index-subscription.spec.ts +20 -13
  40. package/src/index.ts +58 -34
  41. package/src/types.ts +1 -0
  42. package/src/utils/getOrUpdate.spec.ts +168 -0
  43. package/src/utils/getOrUpdate.ts +27 -3
  44. package/dist/actions/authentication.d.ts +0 -4
  45. package/dist/actions/authorization.d.ts +0 -3
  46. package/dist/actions/preferences.d.ts +0 -9
  47. package/dist/actions/preferences.spec.d.ts +0 -1
  48. package/dist/actions/userData.d.ts +0 -2
  49. package/dist/cache/engines/global.d.ts +0 -21
  50. package/dist/cache/engines/global.spec.d.ts +0 -1
  51. package/dist/cache/index.d.ts +0 -11
  52. package/dist/cache/index.spec.d.ts +0 -4
  53. package/dist/cache/types.d.ts +0 -11
  54. package/dist/clients/europa.d.ts +0 -12
  55. package/dist/clients/europa.spec.d.ts +0 -1
  56. package/dist/clients/jupiter.d.ts +0 -30
  57. package/dist/clients/jupiter.spec.d.ts +0 -1
  58. package/dist/clients/mercury.d.ts +0 -18
  59. package/dist/clients/mercury.spec.d.ts +0 -4
  60. package/dist/clients/nebula.d.ts +0 -2
  61. package/dist/clients/nebula.spec.d.ts +0 -1
  62. package/dist/clients/pluto.d.ts +0 -3
  63. package/dist/clients/pluto.spec.d.ts +0 -1
  64. package/dist/eventHandlers/activation.d.ts +0 -15
  65. package/dist/eventHandlers/authentication.d.ts +0 -17
  66. package/dist/eventHandlers/userAttributes.d.ts +0 -14
  67. package/dist/index-authentcation.spec.d.ts +0 -4
  68. package/dist/index-subscription.spec.d.ts +0 -4
  69. package/dist/index-userdata.spec.d.ts +0 -4
  70. package/dist/index.js.LICENSE.txt +0 -14
  71. package/dist/index.js.gz +0 -0
  72. package/dist/lib/cookie.d.ts +0 -5
  73. package/dist/lib/rpc.d.ts +0 -6
  74. package/dist/services/europa.d.ts +0 -12
  75. package/dist/services/europa.spec.d.ts +0 -1
  76. package/dist/services/jupiter.spec.d.ts +0 -1
  77. package/dist/services/mercury.d.ts +0 -18
  78. package/dist/services/mercury.spec.d.ts +0 -4
  79. package/dist/services/nebula.d.ts +0 -22
  80. package/dist/services/nebula.spec.d.ts +0 -1
  81. package/dist/services/pluto.spec.d.ts +0 -1
  82. package/dist/store/index.d.ts +0 -13
  83. package/dist/store/index.spec.d.ts +0 -1
  84. package/dist/store/store.d.ts +0 -13
  85. package/dist/store/store.spec.d.ts +0 -1
  86. package/dist/types.d.ts +0 -24
  87. package/dist/utils/customEventWrapper.d.ts +0 -17
  88. package/dist/utils/deepEquals.d.ts +0 -4
  89. package/dist/utils/getOrUpdate.d.ts +0 -6
  90. package/dist/utils/log.d.ts +0 -26
  91. package/dist/utils/queue.d.ts +0 -12
  92. package/dist/utils/url.d.ts +0 -3
  93. package/dist/utils/url.spec.d.ts +0 -1
@@ -8,8 +8,6 @@ import backendLog, {
8
8
  UserDeactivatedError,
9
9
  } from './mercury';
10
10
 
11
- fetch.enableMocks();
12
-
13
11
  beforeEach(() => {
14
12
  fetch.resetMocks();
15
13
  });
@@ -37,7 +35,7 @@ describe('activateSubscription()', () => {
37
35
  fetch.mockResponse(JSON.stringify({ status: 'user_deactivated' }), {
38
36
  status: 401,
39
37
  });
40
- return expect(activateSubscription('newspaper')).rejects.toThrow(
38
+ expect(activateSubscription(['newspaper'])).rejects.toThrow(
41
39
  UserDeactivatedError
42
40
  );
43
41
  });
@@ -46,25 +44,25 @@ describe('activateSubscription()', () => {
46
44
  fetch.mockResponse(JSON.stringify({ status: 'whatever' }), {
47
45
  status: 401,
48
46
  });
49
- return expect(activateSubscription('newspaper')).resolves.toBe(false);
47
+ expect(activateSubscription(['newspaper'])).resolves.toBe(false);
50
48
  });
51
49
 
52
50
  it('should return false if access is not "granted"', () => {
53
51
  fetch.mockResponse(JSON.stringify({ status: 'success', access: 'denied' }));
54
- return expect(activateSubscription('newspaper')).resolves.toBe(false);
52
+ expect(activateSubscription(['newspaper'])).resolves.toBe(false);
55
53
  });
56
54
 
57
55
  it('should return false if status is not "success"', () => {
58
56
  fetch.mockResponse(
59
57
  JSON.stringify({ status: 'unknown', access: 'granted' })
60
58
  );
61
- return expect(activateSubscription('newspaper')).resolves.toBe(false);
59
+ expect(activateSubscription(['newspaper'])).resolves.toBe(false);
62
60
  });
63
61
 
64
62
  it('should return true if status is "success" and access is "granted"', () => {
65
63
  fetch.mockResponse(
66
64
  JSON.stringify({ status: 'success', access: 'granted' })
67
65
  );
68
- return expect(activateSubscription('newspaper')).resolves.toBe(true);
66
+ expect(activateSubscription(['newspaper'])).resolves.toBe(true);
69
67
  });
70
68
  });
@@ -46,10 +46,12 @@ const log = {
46
46
  export class UserDeactivatedError extends Error {}
47
47
 
48
48
  export const activateSubscription = async (
49
- accessFeature: string
49
+ accessFeatures: string[]
50
50
  ): Promise<boolean> =>
51
51
  fetch(
52
- `/api/mercury/v2/access/activate?publication_wwwdomain=${getCurrentPublicationDomain()}&access_feature=${accessFeature}`,
52
+ `/api/mercury/v2/access/activate?publication_wwwdomain=${getCurrentPublicationDomain()}&access_features=${accessFeatures.join(
53
+ ','
54
+ )}`,
53
55
  {
54
56
  method: 'post',
55
57
  }
@@ -2,8 +2,6 @@ import fetch from 'jest-fetch-mock';
2
2
  import cache from '../cache';
3
3
  import { getCurrentSession, removeSession } from './pluto';
4
4
 
5
- fetch.enableMocks();
6
-
7
5
  beforeEach(async () => {
8
6
  fetch.resetMocks();
9
7
  await cache.clear();
@@ -9,7 +9,7 @@ export enum ActivationEvents {
9
9
  declare global {
10
10
  interface WindowEventMap {
11
11
  [ActivationEvents.REQUEST_ACTIVATION]: CustomEvent<{
12
- accessFeature: string;
12
+ accessFeatures: string[];
13
13
  }>;
14
14
  [ActivationEvents.ON_ACTIVATION_COMPLETE]: CustomEvent<{
15
15
  hasAccess: boolean;
@@ -19,7 +19,7 @@ declare global {
19
19
 
20
20
  export const listenForActivationRequests = () => {
21
21
  listenWithExclusivity(ActivationEvents.REQUEST_ACTIVATION, (evt) => {
22
- activate(evt.detail.accessFeature).then((result) => {
22
+ activate(evt.detail.accessFeatures).then((result) => {
23
23
  dispatch(
24
24
  new CustomEvent(ActivationEvents.ON_ACTIVATION_COMPLETE, {
25
25
  detail: { hasAccess: result },
@@ -6,9 +6,10 @@ import { goToLoginPage, logout } from './index';
6
6
  import { setRootElement } from './utils/customEventWrapper';
7
7
  import * as authentication from './actions/authentication';
8
8
  import { listenForAuthenticationRequests } from './eventHandlers/authentication';
9
+ import restoreAllMocks = jest.restoreAllMocks;
9
10
 
10
11
  beforeEach(() => {
11
- jest.resetAllMocks();
12
+ restoreAllMocks();
12
13
 
13
14
  // We cannot use window as our event root during testing
14
15
  // since tests are executed in parallel.
@@ -2,14 +2,15 @@
2
2
  * @jest-environment jsdom
3
3
  */
4
4
 
5
- import { subscribeToUserAttributes } from './index';
5
+ import { User } from './index';
6
6
  import * as userData from './actions/userData';
7
7
  import { setRootElement } from './utils/customEventWrapper';
8
8
  import { listenForUserAttributeRequests } from './eventHandlers/userAttributes';
9
9
  import store from './store';
10
+ import restoreAllMocks = jest.restoreAllMocks;
10
11
 
11
12
  beforeEach(() => {
12
- jest.resetAllMocks();
13
+ restoreAllMocks();
13
14
 
14
15
  // We cannot use window as our event root during testing
15
16
  // since tests are executed in parallel.
@@ -30,7 +31,7 @@ describe('Public endpoint - userdata', () => {
30
31
  });
31
32
 
32
33
  const onUserUpdate = jest.fn();
33
- subscribeToUserAttributes(['name'], onUserUpdate);
34
+ new User().withAttributes(['name']).subscribe(onUserUpdate);
34
35
 
35
36
  expect(onUserUpdate).toHaveBeenCalledWith({
36
37
  name: 'Donald Duck',
@@ -42,10 +43,13 @@ describe('Public endpoint - userdata', () => {
42
43
  store.set('userAttributes', { name: 'Donald Duck' });
43
44
  });
44
45
 
46
+ const userUpdates = new User();
47
+
45
48
  const onUserUpdate1 = jest.fn();
46
- subscribeToUserAttributes(['name'], onUserUpdate1);
49
+ userUpdates.withAttributes(['name']).subscribe(onUserUpdate1);
50
+
47
51
  const onUserUpdate2 = jest.fn();
48
- subscribeToUserAttributes(['name'], onUserUpdate2);
52
+ userUpdates.withAttributes(['name']).subscribe(onUserUpdate2);
49
53
 
50
54
  expect(onUserUpdate1).toHaveBeenCalledTimes(1);
51
55
  expect(onUserUpdate1).toHaveBeenCalledWith({
@@ -68,11 +72,13 @@ describe('Public endpoint - userdata', () => {
68
72
  store.set('userAttributes', { name: 'Donald Duck' })
69
73
  );
70
74
 
75
+ const userUpdates = new User();
76
+
71
77
  const firstOnUserUpdate = jest.fn();
72
- subscribeToUserAttributes(['name'], firstOnUserUpdate);
78
+ userUpdates.withAttributes(['name']).subscribe(firstOnUserUpdate);
73
79
 
74
80
  const secondOnUserUpdate = jest.fn();
75
- subscribeToUserAttributes(['name'], secondOnUserUpdate);
81
+ userUpdates.withAttributes(['name']).subscribe(secondOnUserUpdate);
76
82
 
77
83
  expect(firstOnUserUpdate).toHaveBeenCalledTimes(2);
78
84
  expect(firstOnUserUpdate).nthCalledWith(1, {});
@@ -95,7 +101,7 @@ describe('Public endpoint - userdata', () => {
95
101
  });
96
102
 
97
103
  const onUserUpdate = jest.fn();
98
- subscribeToUserAttributes(['name'], onUserUpdate);
104
+ new User().withAttributes(['name']).subscribe(onUserUpdate);
99
105
 
100
106
  expect(onUserUpdate).toHaveBeenCalledWith({
101
107
  name: 'Donald Duck',
@@ -111,7 +117,7 @@ describe('Public endpoint - userdata', () => {
111
117
  });
112
118
 
113
119
  const onUserUpdate = jest.fn();
114
- subscribeToUserAttributes(['name', 'email'], onUserUpdate);
120
+ new User().withAttributes(['name', 'email']).subscribe(onUserUpdate);
115
121
 
116
122
  expect(onUserUpdate).toHaveBeenCalledWith({
117
123
  name: 'Donald Duck',
@@ -121,7 +127,7 @@ describe('Public endpoint - userdata', () => {
121
127
 
122
128
  it('should require at least one attribute', () => {
123
129
  const onUserUpdate = jest.fn();
124
- expect(() => subscribeToUserAttributes([], onUserUpdate)).toThrowError(
130
+ expect(() => new User().subscribe(onUserUpdate)).toThrowError(
125
131
  new Error('You must subscribe to at least one attribute')
126
132
  );
127
133
  });
@@ -135,10 +141,10 @@ describe('Public endpoint - userdata', () => {
135
141
  });
136
142
 
137
143
  const firstOnUserUpdate = jest.fn();
138
- subscribeToUserAttributes(['name', 'email'], firstOnUserUpdate);
144
+ new User().withAttributes(['name', 'email']).subscribe(firstOnUserUpdate);
139
145
 
140
146
  const secondOnUserUpdate = jest.fn();
141
- subscribeToUserAttributes(['email'], secondOnUserUpdate);
147
+ new User().withAttributes(['email']).subscribe(secondOnUserUpdate);
142
148
 
143
149
  expect(firstOnUserUpdate).toHaveBeenCalledTimes(1);
144
150
  expect(firstOnUserUpdate).nthCalledWith(1, {
@@ -162,7 +168,8 @@ describe('Public endpoint - userdata', () => {
162
168
 
163
169
  const onUserUpdate = jest.fn();
164
170
  const onStateUpdate = jest.fn();
165
- subscribeToUserAttributes(['name'], onUserUpdate, onStateUpdate);
171
+
172
+ new User().withAttributes(['name']).subscribe(onUserUpdate, onStateUpdate);
166
173
 
167
174
  expect(onUserUpdate).toHaveBeenCalledWith({ name: 'Donald Duck' });
168
175
  expect(onStateUpdate).toHaveBeenCalledWith({ isLoggedIn: true });
package/src/index.ts CHANGED
@@ -10,46 +10,70 @@ import { deepEquals } from './utils/deepEquals';
10
10
  * Enables you to subscribe to the user attributes you care about and
11
11
  * get notified when something changes
12
12
  */
13
- export const subscribeToUserAttributes = <
14
- T extends Array<keyof UserAttributes>
15
- >(
16
- attributes: T,
17
- onUserUpdated: (attributes: Pick<UserAttributes, T[number]>) => void,
18
- onStateUpdated?: (attributes: State) => void
19
- ) => {
20
- if (!attributes || attributes.length === 0) {
21
- throw new Error('You must subscribe to at least one attribute');
13
+
14
+ export class User {
15
+ private attributes: Array<keyof UserAttributes> = [];
16
+
17
+ private namespaces: Array<string> = [];
18
+
19
+ private extraData?: Array<string> = [];
20
+
21
+ withAttributes(attributes: Array<keyof UserAttributes>): this {
22
+ this.attributes = attributes;
23
+ return this;
22
24
  }
23
- let previousUserAttributes: Pick<UserAttributes, T[number]>;
24
- listenForAllEvents(AmediaUserEvents.ON_ATTRIBUTES_UPDATED, (evt) => {
25
- const userAttributes = evt.detail;
26
25
 
27
- // Reduce responseAttributes to match requested attributes
28
- const responseAttributes = attributes.reduce((map, attribute) => {
29
- if (userAttributes[attribute] !== undefined) {
30
- // eslint-disable-next-line no-param-reassign
31
- map[attribute] = userAttributes[attribute];
32
- }
33
- return map;
34
- }, {} as Pick<UserAttributes, T[number]>);
26
+ withStorage(namespaces: Array<string>): this {
27
+ this.namespaces = namespaces;
28
+ return this;
29
+ }
30
+
31
+ withExtraData(extraData?: Array<string>): this {
32
+ this.extraData = extraData;
33
+ return this;
34
+ }
35
35
 
36
- if (deepEquals(previousUserAttributes, responseAttributes)) {
37
- return;
36
+ subscribe(
37
+ onUserUpdated: (attributes: UserAttributes) => void,
38
+ onStateUpdated?: (state: State) => void
39
+ ): void {
40
+ if (!this.attributes || this.attributes.length === 0) {
41
+ throw new Error('You must subscribe to at least one attribute');
38
42
  }
39
- onUserUpdated(responseAttributes);
40
- previousUserAttributes = responseAttributes;
41
- });
42
- if (onStateUpdated) {
43
- listenForAllEvents(AmediaUserEvents.ON_STATE_UPDATED, (evt) => {
44
- onStateUpdated(evt.detail);
43
+ let previousUserAttributes: UserAttributes;
44
+ listenForAllEvents(AmediaUserEvents.ON_ATTRIBUTES_UPDATED, (evt) => {
45
+ const userAttributes = evt.detail;
46
+
47
+ // Reduce responseAttributes to match requested attributes
48
+ const responseAttributes = this.attributes.reduce((map, attribute) => {
49
+ if (userAttributes[attribute] !== undefined) {
50
+ // @ts-ignore
51
+ // eslint-disable-next-line no-param-reassign
52
+ map[attribute] = userAttributes[attribute];
53
+ }
54
+ return map;
55
+ }, {} as UserAttributes);
56
+
57
+ if (deepEquals(previousUserAttributes, responseAttributes)) {
58
+ return;
59
+ }
60
+
61
+ onUserUpdated(responseAttributes);
62
+ previousUserAttributes = responseAttributes;
45
63
  });
64
+
65
+ if (onStateUpdated) {
66
+ listenForAllEvents(AmediaUserEvents.ON_STATE_UPDATED, (evt) => {
67
+ onStateUpdated(evt.detail);
68
+ });
69
+ }
70
+ dispatch(
71
+ new CustomEvent(AmediaUserEvents.REQUEST_USER_ATTRIBUTES, {
72
+ detail: this.attributes,
73
+ })
74
+ );
46
75
  }
47
- dispatch(
48
- new CustomEvent(AmediaUserEvents.REQUEST_USER_ATTRIBUTES, {
49
- detail: attributes,
50
- })
51
- );
52
- };
76
+ }
53
77
 
54
78
  /**
55
79
  * This will, if necessary, trigger a redirect to www.aid.no and return
package/src/types.ts CHANGED
@@ -6,6 +6,7 @@ export type UserAttributes = {
6
6
  extraData?: { [index: string]: unknown };
7
7
  access?: string[];
8
8
  privacyPreferences?: PrivacyPreferences;
9
+ storage?: { [index: string]: unknown };
9
10
  };
10
11
 
11
12
  export type State = {
@@ -0,0 +1,168 @@
1
+ import { Partial, String } from 'runtypes';
2
+ import cache from '../cache';
3
+ import getOrUpdate from './getOrUpdate';
4
+ import queue from './queue';
5
+ import spyOn = jest.spyOn;
6
+ import restoreAllMocks = jest.restoreAllMocks;
7
+
8
+ const schema = Partial({ field: String, extraField: String });
9
+
10
+ beforeEach(async () => {
11
+ restoreAllMocks();
12
+ await cache.clear();
13
+ });
14
+ describe('getOrUpdate', () => {
15
+ it('should fetch if no cache is available', () => {
16
+ const fetcher = jest.fn().mockResolvedValue({
17
+ ttl: 0,
18
+ data: { field: 'fetchedValue' },
19
+ });
20
+ expect(getOrUpdate('client', schema, fetcher))
21
+ .resolves.toEqual({
22
+ field: 'fetchedValue',
23
+ })
24
+ .then(expect(fetcher).toHaveBeenCalled);
25
+ });
26
+
27
+ it('should add to cache after fetching', async () => {
28
+ const cacheSpy = spyOn(cache, 'set');
29
+ await getOrUpdate(
30
+ 'client',
31
+ schema,
32
+ jest.fn().mockResolvedValue({
33
+ ttl: 10,
34
+ data: { field: 'value' },
35
+ })
36
+ );
37
+ expect(cacheSpy).toHaveBeenCalledWith('client', { field: 'value' }, 10);
38
+ });
39
+
40
+ it('should use cache if available instead of fetching', () => {
41
+ spyOn(cache, 'get').mockResolvedValue({
42
+ field: 'cachedValue',
43
+ });
44
+ const fetcher = jest.fn().mockResolvedValue({
45
+ ttl: 0,
46
+ data: { field: 'fetchedValue' },
47
+ });
48
+ expect(getOrUpdate('client', schema, fetcher))
49
+ .resolves.toEqual({ field: 'cachedValue' })
50
+ .then(expect(fetcher).not.toHaveBeenCalled);
51
+ });
52
+
53
+ it('should allow cache qualifier to override valid result', () => {
54
+ spyOn(cache, 'get').mockResolvedValue({
55
+ field: 'cachedValue',
56
+ });
57
+ const fetcher = jest.fn().mockResolvedValue({
58
+ ttl: 0,
59
+ data: { field: 'fetchedValue' },
60
+ });
61
+ const qualifier = jest.fn().mockReturnValue(false);
62
+ expect(getOrUpdate('client', schema, fetcher, qualifier))
63
+ .resolves.toEqual({ field: 'fetchedValue' })
64
+ .then(expect(fetcher).toHaveBeenCalled)
65
+ .then(() =>
66
+ expect(qualifier).toHaveBeenCalledWith({ field: 'cachedValue' })
67
+ );
68
+ });
69
+
70
+ it('should append to existing cache if any', async () => {
71
+ spyOn(cache, 'get').mockResolvedValue({
72
+ field: 'cachedValue',
73
+ });
74
+ const cacheSetSpy = spyOn(cache, 'set');
75
+ await getOrUpdate(
76
+ 'client',
77
+ schema,
78
+ () => Promise.resolve({ ttl: 0, data: { extraField: 'extraValue' } }),
79
+ () => false
80
+ );
81
+ expect(cacheSetSpy).toHaveBeenCalledWith(
82
+ 'client',
83
+ { field: 'cachedValue', extraField: 'extraValue' },
84
+ 0
85
+ );
86
+ });
87
+
88
+ it('should resolve queue on cached data', (done) => {
89
+ let resolvePromise: Function;
90
+ const promise = new Promise((resolve) => {
91
+ resolvePromise = resolve;
92
+ });
93
+ spyOn(cache, 'get').mockReturnValue(promise);
94
+
95
+ expect(
96
+ Promise.all([
97
+ getOrUpdate('client', schema, jest.fn()),
98
+ getOrUpdate('client', schema, jest.fn()),
99
+ getOrUpdate('client', schema, jest.fn()),
100
+ ])
101
+ )
102
+ .resolves.toEqual([
103
+ { field: 'value' },
104
+ { field: 'value' },
105
+ { field: 'value' },
106
+ ])
107
+ .then(done);
108
+
109
+ expect(queue.peekQueueSize('client')).toEqual(3);
110
+
111
+ // @ts-ignore It has been assigned. Promise
112
+ resolvePromise({ field: 'value' });
113
+ });
114
+
115
+ it('should resolve queue on fetched data', (done) => {
116
+ let resolvePromise: Function;
117
+ const promise = new Promise((resolve) => {
118
+ resolvePromise = resolve;
119
+ });
120
+
121
+ spyOn(cache, 'get').mockResolvedValue(null);
122
+
123
+ expect(
124
+ Promise.all([
125
+ getOrUpdate('client', schema, jest.fn().mockReturnValue(promise)),
126
+ getOrUpdate('client', schema, jest.fn()),
127
+ getOrUpdate('client', schema, jest.fn()),
128
+ ])
129
+ )
130
+ .resolves.toEqual([
131
+ { field: 'value' },
132
+ { field: 'value' },
133
+ { field: 'value' },
134
+ ])
135
+ .then(() => expect(queue.peekQueueSize('client')).toEqual(0))
136
+ .then(done);
137
+
138
+ expect(queue.peekQueueSize('client')).toEqual(3);
139
+
140
+ // @ts-ignore It has been assigned. Promise
141
+ resolvePromise({ ttl: 0, data: { field: 'value' } });
142
+ });
143
+
144
+ it('should reject queue if fetching fails', (done) => {
145
+ let rejectPromise: Function;
146
+ const promise = new Promise((resolve, reject) => {
147
+ rejectPromise = reject;
148
+ });
149
+
150
+ spyOn(cache, 'get').mockResolvedValue(null);
151
+
152
+ const a = jest.fn().mockReturnValue(promise);
153
+ const b = jest.fn();
154
+ const c = jest.fn();
155
+
156
+ expect(getOrUpdate('client', schema, a)).rejects.toEqual(undefined);
157
+ expect(getOrUpdate('client', schema, b)).rejects.toEqual(undefined);
158
+ expect(getOrUpdate('client', schema, c))
159
+ .rejects.toEqual(undefined)
160
+ .then(() => expect(queue.peekQueueSize('client')).toEqual(0))
161
+ .then(done);
162
+
163
+ expect(queue.peekQueueSize('client')).toEqual(3);
164
+
165
+ // @ts-ignore It has been assigned. Promise
166
+ rejectPromise();
167
+ });
168
+ });
@@ -7,10 +7,31 @@ export type DataFetcherWithCacheTTL<T extends Runtype> = Promise<{
7
7
  data: Static<T>;
8
8
  }>;
9
9
 
10
+ const mergeCache = (oldCache: unknown, newCache: unknown): unknown => {
11
+ // Since we cannot know how to deal with duplicates when newCache is array
12
+ // always return newCache
13
+ if (!oldCache || Array.isArray(newCache)) {
14
+ return newCache;
15
+ }
16
+
17
+ // TODO: Possible bug? :)
18
+ if (!newCache) {
19
+ return oldCache;
20
+ }
21
+
22
+ if (typeof oldCache === 'object' && typeof newCache === 'object') {
23
+ return { ...oldCache, ...newCache };
24
+ }
25
+
26
+ // Cannot merge (eg type is string etc)
27
+ return newCache;
28
+ };
29
+
10
30
  export default function getOrUpdate<T extends Runtype>(
11
31
  key: string,
12
32
  schema: T,
13
- fetch: () => DataFetcherWithCacheTTL<T>
33
+ fetch: () => DataFetcherWithCacheTTL<T>,
34
+ cacheQualifier?: (cacheData: Static<T>) => boolean
14
35
  ): Promise<Static<T>> {
15
36
  return new Promise((resolve, reject) => {
16
37
  queue.add(key, { resolve, reject });
@@ -19,7 +40,7 @@ export default function getOrUpdate<T extends Runtype>(
19
40
  }
20
41
 
21
42
  cache.get(key, schema).then((cacheResponse) => {
22
- if (cacheResponse) {
43
+ if (cacheResponse && (!cacheQualifier || cacheQualifier(cacheResponse))) {
23
44
  queue.getAll(key).forEach((promise) => {
24
45
  promise.resolve(cacheResponse);
25
46
  });
@@ -27,7 +48,10 @@ export default function getOrUpdate<T extends Runtype>(
27
48
  }
28
49
  fetch()
29
50
  .then((res) => {
30
- cache.set(key, res.data, res.ttl);
51
+ const newCache = cacheResponse
52
+ ? mergeCache(cacheResponse, res.data)
53
+ : res.data;
54
+ cache.set(key, newCache, res.ttl);
31
55
  queue.getAll(key).forEach((promise) => {
32
56
  promise.resolve(res.data);
33
57
  });
@@ -1,4 +0,0 @@
1
- import { UserAttributes } from '../types';
2
- export declare const login: (requestedUrl: string) => void;
3
- export declare const logout: () => Promise<void>;
4
- export declare const getSession: () => Promise<UserAttributes>;
@@ -1,3 +0,0 @@
1
- import { UserAttributes } from '../types';
2
- export declare const getAccess: () => Promise<Pick<UserAttributes, 'access'>>;
3
- export declare const activate: (accessFeature: string) => Promise<boolean>;
@@ -1,9 +0,0 @@
1
- import { Record, Boolean } from 'runtypes';
2
- import { UserAttributes } from '../types';
3
- export declare const PrivacyPreferencesSchema: Record<{
4
- allowResearchUsage: Boolean;
5
- connectWithSurveys: Boolean;
6
- personalizedAds: Boolean;
7
- personalizedContent: Boolean;
8
- }, false>;
9
- export declare const getPrivacyPreferences: () => Promise<UserAttributes>;
@@ -1 +0,0 @@
1
- export {};
@@ -1,2 +0,0 @@
1
- import { UserAttributes } from '../types';
2
- export declare const requestAttributes: (attributes: Array<keyof UserAttributes>) => void;
@@ -1,21 +0,0 @@
1
- import { CacheEntry, Engine } from '../types';
2
- declare global {
3
- interface Window {
4
- amediaUserCache?: {
5
- [index: string]: CacheEntry;
6
- };
7
- }
8
- namespace NodeJS {
9
- interface Global {
10
- amediaUserCache?: {
11
- [index: string]: CacheEntry;
12
- };
13
- }
14
- }
15
- }
16
- export declare const get: (key: string) => Promise<CacheEntry>;
17
- export declare const set: (key: string, data: unknown, expires: number) => Promise<void>;
18
- export declare const remove: (key: string) => Promise<void>;
19
- export declare const clear: () => Promise<void>;
20
- declare const _default: Engine;
21
- export default _default;
@@ -1 +0,0 @@
1
- export {};
@@ -1,11 +0,0 @@
1
- import { Static } from 'runtypes';
2
- import { RuntypeBase } from 'runtypes/lib/runtype';
3
- import { Engine } from './types';
4
- export declare const setCacheEngine: (engine: Engine) => void;
5
- declare const _default: {
6
- get: <T extends RuntypeBase<unknown>>(key: string, validator: T) => Promise<void | Static<T>>;
7
- set: (key: string, value: unknown, expires: number) => Promise<void>;
8
- remove: (key: string) => Promise<void>;
9
- clear: () => Promise<void>;
10
- };
11
- export default _default;
@@ -1,4 +0,0 @@
1
- /**
2
- * @jest-environment jsdom
3
- */
4
- export {};
@@ -1,11 +0,0 @@
1
- export declare type CacheEntry = {
2
- key: string;
3
- data: unknown;
4
- expires: number;
5
- };
6
- export declare type Engine = {
7
- get: (key: string) => Promise<CacheEntry | null>;
8
- set: (key: string, data: unknown, expires: number) => Promise<void>;
9
- remove: (key: string) => Promise<void>;
10
- clear: () => Promise<void>;
11
- };
@@ -1,12 +0,0 @@
1
- import { Record, Partial } from 'runtypes';
2
- export declare const EuropaSchema: Record<{
3
- namespaces: Partial<{}, false>;
4
- }, false>;
5
- export declare const clearLocalCache: () => Promise<void>;
6
- export declare const updateNamespace: (namespace: string, data: Object) => Promise<void | {}>;
7
- export declare const getNamespace: (namespace: string, options?: {
8
- ignoreCache: boolean;
9
- }) => Promise<any>;
10
- export declare const saveNamespace: (namespace: string, data: Object) => Promise<any>;
11
- export declare const getAllNamespaces: () => Promise<{}>;
12
- export declare const deleteNamespaceKey: (namespace: string, key: string) => Promise<any>;
@@ -1 +0,0 @@
1
- export {};