@amedia/user 0.13.26 → 0.13.27

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 (80) hide show
  1. package/amedia-user-js.iml +9 -0
  2. package/checkVersion.js +12 -0
  3. package/dist/cache/engines/indexeddb.d.ts +7 -0
  4. package/dist/clients/europa.d.ts +3 -7
  5. package/dist/index.d.ts +36 -7
  6. package/dist/index.esm.js +1 -1
  7. package/dist/index.esm.js.map +3 -3
  8. package/dist/index.js +1 -1
  9. package/dist/index.js.LICENSE.txt +14 -0
  10. package/dist/index.js.map +3 -3
  11. package/dist/janitor/index.spec.d.ts +4 -0
  12. package/dist/lib/PaywallUnlocker.d.ts +16 -0
  13. package/dist/lib/PaywallUnlocker.spec.d.ts +4 -0
  14. package/dist/lib/User.d.ts +21 -0
  15. package/dist/utils/debouncer.d.ts +26 -0
  16. package/dist/utils/debouncer.spec.d.ts +1 -0
  17. package/dist/utils/logValidationError.d.ts +1 -0
  18. package/eik.json +1 -1
  19. package/esm/actions/authentication.d.ts +5 -0
  20. package/esm/actions/authentication.spec.d.ts +4 -0
  21. package/esm/actions/authorization.d.ts +9 -0
  22. package/esm/actions/preferences.d.ts +9 -0
  23. package/esm/actions/preferences.spec.d.ts +1 -0
  24. package/esm/actions/storage.d.ts +4 -0
  25. package/esm/actions/userData.d.ts +2 -0
  26. package/esm/autologin/index.d.ts +1 -0
  27. package/esm/autologin/thirdPartyCookie.d.ts +3 -0
  28. package/esm/autologin/thirdPartyCookie.spec.d.ts +1 -0
  29. package/esm/cache/engines/global.d.ts +21 -0
  30. package/esm/cache/engines/global.spec.d.ts +1 -0
  31. package/esm/cache/engines/indexeddb.d.ts +7 -0
  32. package/esm/cache/index.d.ts +11 -0
  33. package/esm/cache/index.spec.d.ts +4 -0
  34. package/esm/cache/types.d.ts +11 -0
  35. package/esm/clients/europa.d.ts +28 -0
  36. package/esm/clients/europa.spec.d.ts +1 -0
  37. package/esm/clients/jupiter.d.ts +30 -0
  38. package/esm/clients/jupiter.spec.d.ts +1 -0
  39. package/esm/clients/mercury.d.ts +18 -0
  40. package/esm/clients/mercury.spec.d.ts +4 -0
  41. package/esm/clients/nebula.d.ts +2 -0
  42. package/esm/clients/nebula.spec.d.ts +1 -0
  43. package/esm/clients/pluto.d.ts +3 -0
  44. package/esm/clients/pluto.spec.d.ts +1 -0
  45. package/esm/eventHandlers/activation.d.ts +15 -0
  46. package/esm/eventHandlers/authentication.d.ts +17 -0
  47. package/esm/eventHandlers/userAttributes.d.ts +24 -0
  48. package/esm/exceptions/PaywallError.d.ts +7 -0
  49. package/esm/index-authentcation.spec.d.ts +4 -0
  50. package/esm/index-storage.spec.d.ts +4 -0
  51. package/esm/index-subscription.spec.d.ts +4 -0
  52. package/esm/index.d.ts +26 -0
  53. package/esm/janitor/index.d.ts +10 -0
  54. package/esm/janitor/jobs/accessCookieRefresher.d.ts +1 -0
  55. package/esm/janitor/jobs/accessCookieRefresher.spec.d.ts +4 -0
  56. package/esm/lib/PaywallUnlocker.d.ts +16 -0
  57. package/esm/lib/PaywallUnlocker.spec.d.ts +4 -0
  58. package/esm/lib/User.d.ts +21 -0
  59. package/esm/lib/cookie.d.ts +5 -0
  60. package/esm/lib/rpc.d.ts +6 -0
  61. package/esm/store/index.d.ts +22 -0
  62. package/esm/store/index.spec.d.ts +1 -0
  63. package/esm/types.d.ts +22 -0
  64. package/esm/user.js +2 -0
  65. package/esm/user.js.map +1 -0
  66. package/esm/utils/customEventWrapper.d.ts +17 -0
  67. package/esm/utils/deepEquals.d.ts +4 -0
  68. package/esm/utils/getOrUpdate.d.ts +6 -0
  69. package/esm/utils/getOrUpdate.spec.d.ts +1 -0
  70. package/esm/utils/location.d.ts +3 -0
  71. package/esm/utils/log.d.ts +26 -0
  72. package/esm/utils/queue.d.ts +12 -0
  73. package/esm/utils/url.d.ts +6 -0
  74. package/esm/utils/url.spec.d.ts +1 -0
  75. package/package.json +4 -2
  76. package/src/clients/europa.spec.ts +8 -13
  77. package/src/clients/europa.ts +41 -40
  78. package/src/clients/mercuryLog.ts +3 -1
  79. package/src/utils/debouncer.spec.ts +257 -0
  80. package/src/utils/debouncer.ts +103 -0
@@ -0,0 +1,17 @@
1
+ export declare const setRootElement: (element: any) => void;
2
+ /**
3
+ * This listener MUST be used by all listeners in ../eventHandlers
4
+ * We want to ensure that only _one_ instance of this package actually
5
+ * orchestrates data and performs requests against backends.
6
+ * @param type
7
+ * @param listener
8
+ */
9
+ export declare const listenWithExclusivity: <T extends keyof WindowEventMap>(type: T, listener: (this: Window, ev: WindowEventMap[T]) => void) => void;
10
+ /**
11
+ * Use this for response listeners. (../index.ts) where we want
12
+ * all updates with data - no matter who sent the actual request
13
+ * @param type
14
+ * @param listener
15
+ */
16
+ export declare const listenForAllEvents: <T extends keyof WindowEventMap>(type: T, listener: (this: Window, ev: WindowEventMap[T]) => void) => void;
17
+ export declare const dispatch: <T extends Event>(event: T) => void;
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @see https://dev.to/sanderdebr/deep-equality-checking-of-objects-in-vanilla-javascript-5592
3
+ */
4
+ export declare const deepEquals: (a: unknown, b: unknown) => boolean;
@@ -0,0 +1,6 @@
1
+ import { Runtype, Static } from 'runtypes';
2
+ export declare type DataFetcherWithCacheTTL<T extends Runtype> = Promise<{
3
+ ttl: number;
4
+ data: Static<T>;
5
+ }>;
6
+ export default function getOrUpdate<T extends Runtype>(key: string, schema: T, fetch: () => DataFetcherWithCacheTTL<T>, cacheQualifier?: (cacheData: Static<T>) => boolean): Promise<Static<T>>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export declare const reload: () => void;
2
+ export declare const replace: (requestedUrl: string) => void;
3
+ export declare const navigateTo: (url: string) => void;
@@ -0,0 +1,26 @@
1
+ export declare type Logger = {
2
+ debug: (message: string | any, ...extra: any[]) => void;
3
+ info: (message: string | any, ...extra: any[]) => void;
4
+ warn: (message: string | any, ...extra: any[]) => void;
5
+ error: (message: string | any, ...extra: any[]) => void;
6
+ };
7
+ export declare const setLogger: (engine: Logger) => void;
8
+ declare const _default: {
9
+ debug: {
10
+ (...data: any[]): void;
11
+ (message?: any, ...optionalParams: any[]): void;
12
+ };
13
+ info: {
14
+ (...data: any[]): void;
15
+ (message?: any, ...optionalParams: any[]): void;
16
+ };
17
+ warn: {
18
+ (...data: any[]): void;
19
+ (message?: any, ...optionalParams: any[]): void;
20
+ };
21
+ error: {
22
+ (...data: any[]): void;
23
+ (message?: any, ...optionalParams: any[]): void;
24
+ };
25
+ };
26
+ export default _default;
@@ -0,0 +1,12 @@
1
+ declare const _default: {
2
+ add: (key: string, promiseCallbacks: {
3
+ resolve: (PromiseLike: any) => void;
4
+ reject: (reason?: any) => void;
5
+ }) => void;
6
+ getAll: (key: string) => {
7
+ resolve: (PromiseLike: any) => void;
8
+ reject: (reason?: any) => void;
9
+ }[];
10
+ peekQueueSize: (key: string) => number;
11
+ };
12
+ export default _default;
@@ -0,0 +1,6 @@
1
+ export declare const setCurrentHostname: (hostname: string) => void;
2
+ export declare const getCurrentHostname: () => string;
3
+ export declare const getCurrentUrl: () => string;
4
+ export declare const getCurrentEnvironment: () => string | null;
5
+ export declare const getCurrentPublicationDomain: () => string;
6
+ export declare const getAidDomain: () => string;
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.13.26",
3
+ "version": "0.13.27",
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)",
@@ -13,11 +13,13 @@
13
13
  "build": "npm install && node build.js",
14
14
  "typings": "tsc",
15
15
  "eik:package": "run-p typings lint && npm run test && npm run build && eik package",
16
- "prepublishOnly": "run-p typings lint && npm run test && npm run build"
16
+ "prepublishOnly": "node checkVersion.js && run-p typings lint && npm run test && npm run build",
17
+ "postpublish": "eik package"
17
18
  },
18
19
  "dependencies": {
19
20
  "@amedia/browserid": "^0.1.6",
20
21
  "@amedia/frontend-rpc": "^0.0.12",
22
+ "deep-copy-ts": "^0.5.0",
21
23
  "runtypes": "^6.3.2",
22
24
  "ts-deepmerge": "^1.0.8"
23
25
  },
@@ -44,7 +44,7 @@ describe('Europa', () => {
44
44
  const updated = await updateNamespace('user_info', newUserInfo).then(() =>
45
45
  cache.get('europa', EuropaSchema)
46
46
  );
47
- expect(updated).toMatchObject({ namespaces: { user_info: newUserInfo } });
47
+ expect(updated).toMatchObject({ user_info: newUserInfo });
48
48
  expect(fetch).toHaveBeenCalledTimes(3);
49
49
  });
50
50
 
@@ -53,7 +53,7 @@ describe('Europa', () => {
53
53
 
54
54
  await saveNamespace('euucp', { x: 'x' });
55
55
  expect(cache.get('europa', EuropaSchema)).resolves.toMatchObject({
56
- namespaces: { euucp: { x: 'x' } },
56
+ euucp: { x: 'x' },
57
57
  }); // expect something in cache
58
58
 
59
59
  await clearLocalCache();
@@ -73,7 +73,7 @@ describe('Europa', () => {
73
73
  // expect x and y
74
74
  expect(await cache.get('europa', EuropaSchema)).toEqual(
75
75
  expect.objectContaining({
76
- namespaces: { euucp: data },
76
+ euucp: data,
77
77
  })
78
78
  );
79
79
 
@@ -81,7 +81,7 @@ describe('Europa', () => {
81
81
  // expect only y
82
82
  expect(await cache.get('europa', EuropaSchema)).toEqual(
83
83
  expect.objectContaining({
84
- namespaces: { euucp: { y: 'y' } },
84
+ euucp: { y: 'y' },
85
85
  })
86
86
  );
87
87
  });
@@ -143,8 +143,9 @@ describe('getNamespaces', () => {
143
143
  const data2 = { user_info: { a: 'a' } };
144
144
  let response2: any;
145
145
  beforeEach(async () => {
146
- fetch.mockResponseOnce(JSON.stringify({ namespaces: data }));
147
- fetch.mockResponseOnce(JSON.stringify({ namespaces: data2 }));
146
+ fetch.mockResponseOnce(
147
+ JSON.stringify({ namespaces: { ...data, ...data2 } })
148
+ );
148
149
  const futureEuucp = getNamespaces(['euucp']);
149
150
  response2 = await getNamespaces(['user_info']);
150
151
  response = await futureEuucp;
@@ -161,13 +162,7 @@ describe('getNamespaces', () => {
161
162
  describe('with one namespace in cache', () => {
162
163
  const data = { euucp: { x: 'x' } };
163
164
  beforeEach(() => {
164
- cache.set(
165
- 'europa',
166
- {
167
- namespaces: data,
168
- },
169
- 100000
170
- );
165
+ cache.set('europa', data, 100000);
171
166
  });
172
167
 
173
168
  describe('when requesting cached namespace', () => {
@@ -1,12 +1,14 @@
1
- import { Record, Unknown, Dictionary, String, Static } from 'runtypes';
1
+ import { Unknown, Dictionary, String, Static } from 'runtypes';
2
2
 
3
3
  import cache from '../cache';
4
4
  import getOrUpdate from '../utils/getOrUpdate';
5
5
  import log from '../utils/log';
6
+ import Debouncer from '../utils/debouncer';
6
7
 
7
8
  const CACHE_DURATION = 5 * 60000; // 5 minutes
9
+ const DEBOUNCE_WAIT_TIME = 20; // 20ms wait before actually calling Europa
8
10
 
9
- export const EuropaSchema = Record({ namespaces: Dictionary(Unknown, String) });
11
+ export const EuropaSchema = Dictionary(Unknown, String);
10
12
 
11
13
  export const clearLocalCache = () => cache.remove('europa');
12
14
 
@@ -21,25 +23,21 @@ const doFetch = (url: string, method: string = 'GET', body?: Object) =>
21
23
  });
22
24
 
23
25
  function mergeCache(
24
- cachedData: Static<typeof EuropaSchema>,
26
+ cachedData: Static<typeof EuropaSchema> | void,
25
27
  newData: Static<typeof EuropaSchema>
26
28
  ) {
27
- return {
28
- namespaces: Object.entries(newData.namespaces).reduce(
29
- (mergedNamespaces, [namespace, data]) => ({
30
- ...mergedNamespaces,
31
- [namespace]: data,
32
- }),
33
- cachedData?.namespaces || {}
34
- ),
35
- };
29
+ return Object.entries(newData).reduce(
30
+ (mergedNamespaces, [namespace, data]) => ({
31
+ ...mergedNamespaces,
32
+ [namespace]: data,
33
+ }),
34
+ cachedData || {}
35
+ );
36
36
  }
37
37
 
38
38
  const updateNamespaceInCache = async (namespace: string, data: Object) => {
39
39
  const cachedData = await cache.get('europa', EuropaSchema);
40
- const updatedData = mergeCache(cachedData || { namespaces: {} }, {
41
- namespaces: { [namespace]: data },
42
- });
40
+ const updatedData = mergeCache(cachedData, { [namespace]: data });
43
41
  return cache.set('europa', updatedData, Date.now() + CACHE_DURATION);
44
42
  };
45
43
 
@@ -55,6 +53,27 @@ export const updateNamespace = async (namespace: string, data: Object) => {
55
53
  return updateNamespaceInCache(namespace, data);
56
54
  };
57
55
 
56
+ const debouncer = new Debouncer<string[], typeof EuropaSchema>(
57
+ DEBOUNCE_WAIT_TIME,
58
+ [],
59
+ Debouncer.stringListParamsAccumulator,
60
+ (params) =>
61
+ doFetch(`/api/europa/v1/me/${params.join(',')}`).then(async (response) => {
62
+ const body = await response.text();
63
+ if (!response.ok) {
64
+ // TODO we should possibly extend Europa to say what param we're missing so we can ignore missing aid.session cookie
65
+ if (response.status !== 400) {
66
+ log.error(
67
+ `Could not get namespaces for: ${params}, status: ${response.status}`,
68
+ { response, body }
69
+ );
70
+ }
71
+ return {};
72
+ }
73
+ return JSON.parse(body).namespaces;
74
+ })
75
+ );
76
+
58
77
  export const getNamespaces = async <
59
78
  S extends { [namespace: string]: { [index: string]: unknown } },
60
79
  Namespaces extends Array<keyof S>
@@ -75,42 +94,24 @@ export const getNamespaces = async <
75
94
  cachedData
76
95
  ? namespaces.filter(
77
96
  (namespace) =>
78
- !Object.keys(cachedData.namespaces).includes(namespace as string)
97
+ !Object.keys(cachedData).includes(namespace as string)
79
98
  )
80
99
  : namespaces
81
100
  ) as string[];
82
101
  if (cachedData && missingNamespaces.length === 0) {
83
102
  // Yay! Everything we need is in the cache!
84
- return Promise.resolve(
85
- cachedData.namespaces as Pick<S, Namespaces[number]>
86
- );
103
+ return Promise.resolve(cachedData as Pick<S, Namespaces[number]>);
87
104
  }
88
105
  }
89
106
 
90
- const fetchedNamespaces = await doFetch(
91
- `/api/europa/v1/me/${missingNamespaces.join(',')}`
92
- ).then(async (response) => {
93
- const body = await response.text();
94
- if (!response.ok) {
95
- // TODO we should possibly extend Europa to say what param we're missing so we can ignore missing aid.session cookie
96
- if (response.status !== 400) {
97
- log.error(
98
- `Could not get namespaces for: ${namespaces}, status: ${response.status}`,
99
- { response, body }
100
- );
101
- }
102
- return { namespaces: {} };
103
- }
104
- return JSON.parse(body);
105
- });
106
-
107
- Object.entries(fetchedNamespaces.namespaces).forEach(
108
- ([namespace, fetchedNamespace]) =>
109
- updateNamespaceInCache(namespace, fetchedNamespace as Object)
107
+ const fetchedNamespaces = await debouncer.perform(missingNamespaces);
108
+ Object.entries(fetchedNamespaces).forEach(([namespace, fetchedNamespace]) =>
109
+ updateNamespaceInCache(namespace, fetchedNamespace as Object)
110
110
  );
111
111
 
112
112
  return Promise.resolve(
113
- Object.entries(mergeCache(cachedData, fetchedNamespaces).namespaces)
113
+ // @ts-ignore
114
+ Object.entries(mergeCache(cachedData, fetchedNamespaces))
114
115
  .filter(([namespace]) => namespaces.includes(namespace))
115
116
  .reduce(
116
117
  (returnedEntries, [namespace, data]) => ({
@@ -18,7 +18,9 @@ function postLog(url: string, query: { [index: string]: any }) {
18
18
  };
19
19
  fetch(url, options).then((res) => {
20
20
  if (!res.ok) {
21
- throw new Error(`Error, status: ${res.status}, text: ${res.statusText}`);
21
+ console.error(
22
+ `Failed to send log to backend: Error, status: ${res.status}, text: ${res.statusText}`
23
+ );
22
24
  }
23
25
  });
24
26
  }
@@ -0,0 +1,257 @@
1
+ import restoreAllMocks = jest.restoreAllMocks;
2
+ import Debouncer from './debouncer';
3
+
4
+ beforeEach(async () => {
5
+ restoreAllMocks();
6
+ });
7
+
8
+ describe('Debouncer', () => {
9
+ describe('when params is list of arrays and response is key value object', () => {
10
+ let debouncer: Debouncer<string[], Record<string, string>>;
11
+ const params1 = ['foo', 'bar'];
12
+ const params2 = ['baz', '1337'];
13
+ describe('when workload succeeds', () => {
14
+ beforeEach(() => {
15
+ debouncer = new Debouncer<string[], Record<string, string>>(
16
+ 10,
17
+ [],
18
+ Debouncer.stringListParamsAccumulator,
19
+ (params) =>
20
+ Promise.resolve(
21
+ params.reduce(
22
+ (map, param): Record<string, string> => ({
23
+ ...map,
24
+ [param]: param.toUpperCase(),
25
+ }),
26
+ {} as Record<string, string>
27
+ )
28
+ )
29
+ );
30
+ });
31
+ describe('when called in quick succession', () => {
32
+ let result1: Record<string, string>;
33
+ let result2: Record<string, string>;
34
+ const expectedResult = {
35
+ foo: 'FOO',
36
+ bar: 'BAR',
37
+ baz: 'BAZ',
38
+ 1337: '1337',
39
+ };
40
+ beforeEach(async () => {
41
+ const promise1 = debouncer.perform(params1);
42
+ const promise2 = debouncer.perform(params2);
43
+ result1 = await promise1;
44
+ result2 = await promise2;
45
+ });
46
+ it('Resolution to first promise is complete set', () => {
47
+ expect(result1).toEqual(expectedResult);
48
+ });
49
+ it('Resolution to second promise is complete set', () => {
50
+ expect(result2).toEqual(expectedResult);
51
+ });
52
+ });
53
+ describe('when waiting for first resolution before second call', () => {
54
+ let result1: Record<string, string>;
55
+ let result2: Record<string, string>;
56
+ const expectedResult1 = {
57
+ foo: 'FOO',
58
+ bar: 'BAR',
59
+ };
60
+ const expectedResult2 = {
61
+ baz: 'BAZ',
62
+ 1337: '1337',
63
+ };
64
+ beforeEach(async () => {
65
+ result1 = await debouncer.perform(params1);
66
+ result2 = await debouncer.perform(params2);
67
+ });
68
+ it('Resolution to first promise is only result of first set', () => {
69
+ expect(result1).toEqual(expectedResult1);
70
+ });
71
+ it('Resolution to second promise is only result of second set', () => {
72
+ expect(result2).toEqual(expectedResult2);
73
+ });
74
+ });
75
+ });
76
+ describe('when workload fails', () => {
77
+ beforeEach(() => {
78
+ debouncer = new Debouncer<string[], Record<string, string>>(
79
+ 10,
80
+ [],
81
+ Debouncer.stringListParamsAccumulator,
82
+ (params) =>
83
+ Promise.reject(new Error(`Cannot handle ${params.join(',')}`))
84
+ );
85
+ });
86
+ describe('when called in quick succession', () => {
87
+ let result1: string;
88
+ let result2: string;
89
+ beforeEach(async () => {
90
+ const promise1 = debouncer.perform(params1);
91
+ const promise2 = debouncer.perform(params2);
92
+ try {
93
+ await promise1;
94
+ } catch (e) {
95
+ result1 = e.message;
96
+ }
97
+ try {
98
+ await promise2;
99
+ } catch (e) {
100
+ result2 = e.message;
101
+ }
102
+ });
103
+ it('Resolution to first promise is error handling all params', () => {
104
+ expect(result1).toEqual('Cannot handle foo,bar,baz,1337');
105
+ });
106
+ it('Resolution to second promise is error handling all params', async () => {
107
+ expect(result2).toEqual('Cannot handle foo,bar,baz,1337');
108
+ });
109
+ });
110
+ describe('when waiting for first resolution before second call', () => {
111
+ let result1: string;
112
+ let result2: string;
113
+ beforeEach(async () => {
114
+ try {
115
+ await debouncer.perform(params1);
116
+ } catch (e) {
117
+ result1 = e.message;
118
+ }
119
+ try {
120
+ await debouncer.perform(params2);
121
+ } catch (e) {
122
+ result2 = e.message;
123
+ }
124
+ });
125
+ it('Resolution to first promise is error handling first set', () => {
126
+ expect(result1).toEqual('Cannot handle foo,bar');
127
+ });
128
+ it('Resolution to second promise is error handling second set', () => {
129
+ expect(result2).toEqual('Cannot handle baz,1337');
130
+ });
131
+ });
132
+ });
133
+ });
134
+ describe('when params is key value object response is list of strings', () => {
135
+ let debouncer: Debouncer<Record<string, string>, string[]>;
136
+ const params1 = {
137
+ foo: 'FOO',
138
+ bar: 'BAR',
139
+ };
140
+ const params2 = {
141
+ baz: 'BAZ',
142
+ 1337: '1337',
143
+ };
144
+ describe('when workload succeeds', () => {
145
+ beforeEach(() => {
146
+ debouncer = new Debouncer<Record<string, string>, string[]>(
147
+ 10,
148
+ {},
149
+ Debouncer.stringMapParamsAccumulator,
150
+ (params) =>
151
+ Promise.resolve(Object.entries(params).map(([k, v]) => `${k}=${v}`))
152
+ );
153
+ });
154
+
155
+ describe('when called in quick succession', () => {
156
+ let result1: string[];
157
+ let result2: string[];
158
+ const expectedResult = ['1337=1337', 'foo=FOO', 'bar=BAR', 'baz=BAZ'];
159
+ beforeEach(async () => {
160
+ const promise1 = debouncer.perform(params1);
161
+ const promise2 = debouncer.perform(params2);
162
+ result1 = await promise1;
163
+ result2 = await promise2;
164
+ });
165
+ it('Resolution to first promise is complete set', () => {
166
+ expect(result1).toEqual(expectedResult);
167
+ });
168
+ it('Resolution to second promise is complete set', () => {
169
+ expect(result2).toEqual(expectedResult);
170
+ });
171
+ });
172
+ describe('when waiting for first resolution before second call', () => {
173
+ let result1: string[];
174
+ let result2: string[];
175
+ const expectedResult1 = ['foo=FOO', 'bar=BAR'];
176
+ const expectedResult2 = ['1337=1337', 'baz=BAZ'];
177
+ beforeEach(async () => {
178
+ result1 = await debouncer.perform(params1);
179
+ result2 = await debouncer.perform(params2);
180
+ });
181
+ it('Resolution to first promise is only result of first set', () => {
182
+ expect(result1).toEqual(expectedResult1);
183
+ });
184
+ it('Resolution to second promise is only result of second set', () => {
185
+ expect(result2).toEqual(expectedResult2);
186
+ });
187
+ });
188
+ });
189
+ describe('when workload fails', () => {
190
+ beforeEach(() => {
191
+ debouncer = new Debouncer<Record<string, string>, string[]>(
192
+ 10,
193
+ {},
194
+ Debouncer.stringMapParamsAccumulator,
195
+ (params) =>
196
+ Promise.reject(
197
+ new Error(
198
+ `Cannot handle ${Object.entries(params)
199
+ .map(([k, v]) => `${k}=${v}`)
200
+ .join(',')}`
201
+ )
202
+ )
203
+ );
204
+ });
205
+ describe('when called in quick succession', () => {
206
+ let result1: string;
207
+ let result2: string;
208
+ beforeEach(async () => {
209
+ const promise1 = debouncer.perform(params1);
210
+ const promise2 = debouncer.perform(params2);
211
+ try {
212
+ await promise1;
213
+ } catch (e) {
214
+ result1 = e.message;
215
+ }
216
+ try {
217
+ await promise2;
218
+ } catch (e) {
219
+ result2 = e.message;
220
+ }
221
+ });
222
+ it('Resolution to first promise is error handling all params', () => {
223
+ expect(result1).toEqual(
224
+ 'Cannot handle 1337=1337,foo=FOO,bar=BAR,baz=BAZ'
225
+ );
226
+ });
227
+ it('Resolution to second promise is error handling all params', async () => {
228
+ expect(result2).toEqual(
229
+ 'Cannot handle 1337=1337,foo=FOO,bar=BAR,baz=BAZ'
230
+ );
231
+ });
232
+ });
233
+ describe('when waiting for first resolution before second call', () => {
234
+ let result1: string;
235
+ let result2: string;
236
+ beforeEach(async () => {
237
+ try {
238
+ await debouncer.perform(params1);
239
+ } catch (e) {
240
+ result1 = e.message;
241
+ }
242
+ try {
243
+ await debouncer.perform(params2);
244
+ } catch (e) {
245
+ result2 = e.message;
246
+ }
247
+ });
248
+ it('Resolution to first promise is error handling first set', () => {
249
+ expect(result1).toEqual('Cannot handle foo=FOO,bar=BAR');
250
+ });
251
+ it('Resolution to second promise is error handling second set', () => {
252
+ expect(result2).toEqual('Cannot handle 1337=1337,baz=BAZ');
253
+ });
254
+ });
255
+ });
256
+ });
257
+ });
@@ -0,0 +1,103 @@
1
+ import { deepCopy } from 'deep-copy-ts';
2
+ import deepmerge from 'ts-deepmerge';
3
+
4
+ /**
5
+ * The Debouncer can be used when we want a clean way to say 'I want to fetch this and that, and once it's done,
6
+ * resolve my promise', but instead of the fetch being performed right away, we want to wait for more users to
7
+ * request other stuff. This will keep us from performing lots of individual fetches to the backend.
8
+ *
9
+ * Our main use case is a standard publication front page where one component on the page requests the euucp namespace
10
+ * from Europa, and then another component requests the privacy_preferences namespace. Instead of the Europa client
11
+ * calling two fetches to the server, one for euucp and another for privacy_preferences, we want the Debouncer to
12
+ * aggregate these calls into one call to the backend, that requests both euucp AND privacy_preferences, so the response
13
+ * to both components will be both namespaces (which the Europa client can filter before it actually reaches the
14
+ * component).
15
+ */
16
+ class Debouncer<ParamsType, ResultType> {
17
+ private timer: ReturnType<typeof setTimeout> | undefined;
18
+
19
+ private params: ParamsType;
20
+
21
+ private queue: {
22
+ resolve: (arg0: any) => void;
23
+ reject: (reason?: any) => void;
24
+ }[] = [];
25
+
26
+ constructor(
27
+ // The number of milliseconds to wait for new calls to perform before actually performing workload
28
+ private timeoutMs: number,
29
+
30
+ // Default parameters if none provided, normally an empty object or list
31
+ private defaultParams: ParamsType,
32
+
33
+ // Function that can accumulate parameters from successive calls to perform, see examples below
34
+ private paramAccumulator: (
35
+ previousParams: ParamsType,
36
+ newParams: ParamsType
37
+ ) => ParamsType,
38
+
39
+ // The workload we want to perform on accumulated parameters once timeout has been reached
40
+ private workload: (params: ParamsType) => Promise<ResultType>
41
+ ) {
42
+ this.params = deepCopy(defaultParams);
43
+ }
44
+
45
+ // Caller indicates that it wants to perform workload on a set of parameters. We will wait this.timeoutMs milliseconds
46
+ // and see if we get more calls to perform workload, if we do, we accumulate parameters and wait this.timeoutMs
47
+ // more milliseconds until we finally perform workload and resolve promises.
48
+ perform(newParams: ParamsType): Promise<ResultType> {
49
+ return new Promise((resolve, reject) => {
50
+ if (this.timer) {
51
+ clearTimeout(this.timer);
52
+ }
53
+ this.params = this.paramAccumulator(this.params, newParams);
54
+ this.queue.push({ resolve, reject });
55
+ this.timer = setTimeout(async () => {
56
+ // Copy current state to use for performing workload and resolving promises after workload completes
57
+ const params = deepCopy(this.params);
58
+ const promisesToKeep = [...this.queue];
59
+
60
+ // Setup new clean state for future calls to perform
61
+ this.params = this.defaultParams;
62
+ this.queue = [];
63
+
64
+ // Perform workload and resolve promises for all callers with result
65
+ this.workload(params)
66
+ .then((result) => {
67
+ promisesToKeep.forEach((promise) => {
68
+ promise.resolve(result);
69
+ });
70
+ })
71
+ .catch((e) => {
72
+ // If workload fails, we need to reject all promises so callers won't be left hanging
73
+ promisesToKeep.forEach((promise) => {
74
+ promise.reject(e);
75
+ });
76
+ });
77
+ }, this.timeoutMs);
78
+ });
79
+ }
80
+
81
+ // Accumulate parameters as lists of strings
82
+ static stringListParamsAccumulator(
83
+ accumulatedParams: string[],
84
+ newParams: string[]
85
+ ) {
86
+ newParams.forEach((param) => {
87
+ if (!accumulatedParams.includes(param)) {
88
+ accumulatedParams.push(param);
89
+ }
90
+ });
91
+ return accumulatedParams;
92
+ }
93
+
94
+ // Accumulate parameters as map with string keys
95
+ static stringMapParamsAccumulator(
96
+ previousParams: Record<string, any>,
97
+ newParams: Record<string, any>
98
+ ) {
99
+ return deepmerge(previousParams, newParams);
100
+ }
101
+ }
102
+
103
+ export default Debouncer;