@amedia/user 0.13.39 → 0.13.41

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 (86) hide show
  1. package/dist/user.cjs +1 -1
  2. package/dist/user.cjs.map +3 -3
  3. package/dist/user.d.ts +5 -5
  4. package/dist/user.js +1 -1
  5. package/dist/user.js.map +3 -3
  6. package/package.json +5 -3
  7. package/src/actions/authentication.spec.ts +51 -0
  8. package/src/actions/authentication.ts +43 -0
  9. package/src/actions/authorization.spec.ts +369 -0
  10. package/src/actions/authorization.ts +117 -0
  11. package/src/actions/preferences.spec.ts +41 -0
  12. package/src/actions/preferences.ts +41 -0
  13. package/src/actions/storage.ts +22 -0
  14. package/src/actions/userData.spec.ts +133 -0
  15. package/src/actions/userData.ts +68 -0
  16. package/src/autologin/index.spec.ts +239 -0
  17. package/src/autologin/index.ts +92 -0
  18. package/src/autologin/thirdPartyCookie.spec.ts +95 -0
  19. package/src/autologin/thirdPartyCookie.ts +55 -0
  20. package/src/cache/engines/global.spec.ts +62 -0
  21. package/src/cache/engines/global.ts +49 -0
  22. package/src/cache/index.spec.ts +130 -0
  23. package/src/cache/index.ts +48 -0
  24. package/src/cache/types.ts +12 -0
  25. package/src/clients/europa.spec.ts +209 -0
  26. package/src/clients/europa.ts +183 -0
  27. package/src/clients/jupiter.spec.ts +179 -0
  28. package/src/clients/jupiter.ts +119 -0
  29. package/src/clients/mercury.spec.ts +59 -0
  30. package/src/clients/mercury.ts +48 -0
  31. package/src/clients/mercuryLog.spec.ts +20 -0
  32. package/src/clients/mercuryLog.ts +67 -0
  33. package/src/clients/nebula.spec.ts +70 -0
  34. package/src/clients/nebula.ts +83 -0
  35. package/src/clients/pluto.spec.ts +165 -0
  36. package/src/clients/pluto.ts +118 -0
  37. package/src/eventHandlers/activation.ts +36 -0
  38. package/src/eventHandlers/authentication.ts +34 -0
  39. package/src/eventHandlers/eventMap.ts +34 -0
  40. package/src/eventHandlers/state.spec.ts +48 -0
  41. package/src/eventHandlers/state.ts +23 -0
  42. package/src/eventHandlers/storage.spec.ts +114 -0
  43. package/src/eventHandlers/storage.ts +45 -0
  44. package/src/eventHandlers/userAttributes.spec.ts +93 -0
  45. package/src/eventHandlers/userAttributes.ts +31 -0
  46. package/src/exceptions/FetchTimeoutError.ts +8 -0
  47. package/src/exceptions/PaywallError.ts +16 -0
  48. package/src/index-authentcation.spec.ts +26 -0
  49. package/src/index-storage.spec.ts +144 -0
  50. package/src/index-subscription.spec.ts +213 -0
  51. package/src/index.ts +40 -0
  52. package/src/janitor/index.spec.ts +18 -0
  53. package/src/janitor/index.ts +59 -0
  54. package/src/janitor/jobs/accessCookieRefresher.spec.ts +213 -0
  55. package/src/janitor/jobs/accessCookieRefresher.ts +98 -0
  56. package/src/janitor/jobs/daxsubCookie.spec.ts +109 -0
  57. package/src/janitor/jobs/daxsubCookie.ts +38 -0
  58. package/src/janitor/jobs/removeUserStorage.spec.ts +34 -0
  59. package/src/janitor/jobs/removeUserStorage.ts +12 -0
  60. package/src/lib/PaywallUnlockRequest.spec.ts +363 -0
  61. package/src/lib/PaywallUnlockRequest.ts +143 -0
  62. package/src/lib/UserDataRequest.spec.ts +231 -0
  63. package/src/lib/UserDataRequest.ts +267 -0
  64. package/src/lib/cookie.ts +121 -0
  65. package/src/lib/rpc.ts +19 -0
  66. package/src/store/index.spec.ts +49 -0
  67. package/src/store/index.ts +64 -0
  68. package/src/types.ts +22 -0
  69. package/src/utils/customEventWrapper.ts +58 -0
  70. package/src/utils/debouncer.spec.ts +252 -0
  71. package/src/utils/debouncer.ts +123 -0
  72. package/src/utils/deepEquals.ts +42 -0
  73. package/src/utils/expectBootLogs.ts +9 -0
  74. package/src/utils/getGlobalThis.ts +17 -0
  75. package/src/utils/getOrUpdate.spec.ts +166 -0
  76. package/src/utils/getOrUpdate.ts +66 -0
  77. package/src/utils/localhostCheck.ts +10 -0
  78. package/src/utils/location.ts +31 -0
  79. package/src/utils/log.spec.ts +148 -0
  80. package/src/utils/log.ts +124 -0
  81. package/src/utils/loginState.ts +24 -0
  82. package/src/utils/networkError.ts +11 -0
  83. package/src/utils/queue.ts +32 -0
  84. package/src/utils/type.ts +19 -0
  85. package/src/utils/url.spec.ts +33 -0
  86. package/src/utils/url.ts +37 -0
@@ -0,0 +1,62 @@
1
+ import { clear, get, remove, set } from './global';
2
+
3
+ beforeEach(() => {
4
+ global.amediaUserCache = {};
5
+ });
6
+
7
+ describe('Global / window cache', () => {
8
+ it('should return undefined if not in cache', () => {
9
+ expect(get('test')).resolves.toBeUndefined();
10
+ });
11
+
12
+ it('should return if in cache', () => {
13
+ set('test', 'value', 1000);
14
+ expect(get('test')).resolves.toEqual({
15
+ key: 'test',
16
+ data: 'value',
17
+ expires: 1000,
18
+ });
19
+ expect(global.amediaUserCache).toEqual({
20
+ test: { key: 'test', data: 'value', expires: 1000 },
21
+ });
22
+ });
23
+
24
+ it('should be able to set most data', () => {
25
+ set('numeric', 5, 0);
26
+ expect(get('numeric')).resolves.toEqual({
27
+ key: 'numeric',
28
+ data: 5,
29
+ expires: 0,
30
+ });
31
+
32
+ set('object', { name: 'Donald Duck' }, 0);
33
+ expect(get('object')).resolves.toEqual({
34
+ key: 'object',
35
+ data: { name: 'Donald Duck' },
36
+ expires: 0,
37
+ });
38
+ });
39
+
40
+ it('should overwrite existing data', () => {
41
+ set('test', 'data', 0);
42
+ set('test', 'other', 0);
43
+ expect(get('test')).resolves.toEqual({
44
+ key: 'test',
45
+ data: 'other',
46
+ expires: 0,
47
+ });
48
+ });
49
+
50
+ it('should remove data from cache', () => {
51
+ set('test', 'value', 0);
52
+ expect(get('test')).resolves.not.toBeUndefined();
53
+ remove('test');
54
+ expect(get('test')).resolves.toBeUndefined();
55
+ });
56
+
57
+ it('should clear cache', () => {
58
+ set('test', 'value', 0);
59
+ clear();
60
+ expect(global.amediaUserCache).toEqual({});
61
+ });
62
+ });
@@ -0,0 +1,49 @@
1
+ import { CacheEntry, Engine } from '../types';
2
+ import getGlobalThis from '../../utils/getGlobalThis';
3
+
4
+ declare global {
5
+ // eslint-disable-next-line import/no-mutable-exports,no-var
6
+ export var amediaUserCache: { [index: string]: CacheEntry };
7
+
8
+ interface Window {
9
+ amediaUserCache?: { [index: string]: CacheEntry };
10
+ }
11
+
12
+ namespace NodeJS {
13
+ interface Global {
14
+ amediaUserCache?: { [index: string]: CacheEntry };
15
+ }
16
+ }
17
+ }
18
+
19
+ const getStorage = () => {
20
+ const rootObject = globalThis;
21
+ // eslint-disable-next-line no-return-assign
22
+ return rootObject.amediaUserCache || (rootObject.amediaUserCache = {});
23
+ };
24
+
25
+ export const get = (key: string): Promise<CacheEntry> => {
26
+ const data = getStorage()[key];
27
+ return Promise.resolve(data);
28
+ };
29
+
30
+ export const set = (
31
+ key: string,
32
+ data: unknown,
33
+ expires: number
34
+ ): Promise<void> => {
35
+ getStorage()[key] = { key, data, expires };
36
+ return Promise.resolve();
37
+ };
38
+
39
+ export const remove = (key: string): Promise<void> => {
40
+ delete getStorage()[key];
41
+ return Promise.resolve();
42
+ };
43
+
44
+ export const clear = (): Promise<void> => {
45
+ getGlobalThis().amediaUserCache = {};
46
+ return Promise.resolve();
47
+ };
48
+
49
+ export default { get, set, remove, clear } as Engine;
@@ -0,0 +1,130 @@
1
+ import { Record, String } from 'runtypes';
2
+ import * as MockDate from 'mockdate';
3
+ import cache, { setCacheEngine } from '.';
4
+ import { setLogger } from '../utils/log';
5
+
6
+ const TestDataSchema = Record({
7
+ test: String,
8
+ });
9
+
10
+ let log: any;
11
+ let mockEngine: any;
12
+ beforeEach(() => {
13
+ MockDate.reset();
14
+ // @ts-ignore
15
+ mockEngine = {
16
+ get: jest.fn(),
17
+ set: jest.fn(),
18
+ remove: jest.fn(),
19
+ clear: jest.fn(),
20
+ };
21
+ // @ts-ignore
22
+ setCacheEngine(mockEngine);
23
+ log = {
24
+ error: jest.fn(),
25
+ };
26
+ setLogger(log);
27
+ });
28
+
29
+ describe('Cache', () => {
30
+ describe('get', () => {
31
+ it('should get from engine', () => {
32
+ mockEngine.get.mockReturnValueOnce(Promise.resolve(null));
33
+ expect(cache.get('foo', TestDataSchema)).resolves.toBeUndefined();
34
+ expect(mockEngine.get).toHaveBeenCalledWith('foo');
35
+ });
36
+
37
+ it('should validate valid data from engine', () => {
38
+ mockEngine.get.mockReturnValueOnce(
39
+ Promise.resolve({
40
+ key: 'foo',
41
+ data: {
42
+ test: 'cache',
43
+ },
44
+ expires: Date.now() + 1000,
45
+ })
46
+ );
47
+ expect(cache.get('foo', TestDataSchema)).resolves.toEqual({
48
+ test: 'cache',
49
+ });
50
+ });
51
+
52
+ it('should return undefined and delete record on invalid data', async () => {
53
+ mockEngine.get.mockReturnValueOnce(
54
+ Promise.resolve({
55
+ key: 'foo',
56
+ data: {
57
+ invalid: 'data',
58
+ },
59
+ expires: Date.now() + 1000,
60
+ })
61
+ );
62
+ await expect(cache.get('foo', TestDataSchema)).resolves.toBeUndefined();
63
+ expect(mockEngine.get).toHaveBeenCalledWith('foo');
64
+ expect(mockEngine.remove).toHaveBeenCalledWith('foo');
65
+ expect(log.error).toHaveBeenCalledWith(
66
+ 'Expected { test: string; }, but was incompatible',
67
+ {
68
+ error: {
69
+ code: 'CONTENT_INCORRECT',
70
+ details: {
71
+ test: 'Expected string, but was missing',
72
+ },
73
+ message: 'Expected { test: string; }, but was incompatible',
74
+ name: 'ValidationError',
75
+ stack: expect.stringMatching(
76
+ /ValidationError: Expected \{ test: string; \}, but was incompatible\n(^\s+at\s.+$\n){3,}/m
77
+ ),
78
+ },
79
+ cacheData: { invalid: 'data' },
80
+ origin: '@amedia/user',
81
+ }
82
+ );
83
+ });
84
+
85
+ it('deletes expired data', async () => {
86
+ mockEngine.get.mockReturnValueOnce(
87
+ Promise.resolve({
88
+ key: 'foo',
89
+ data: {
90
+ test: 'cache',
91
+ },
92
+ expires: Date.now() - 1000,
93
+ })
94
+ );
95
+ await expect(cache.get('foo', TestDataSchema)).resolves.toBeUndefined();
96
+ expect(mockEngine.get).toHaveBeenCalledWith('foo');
97
+ expect(mockEngine.remove).toHaveBeenCalledWith('foo');
98
+ });
99
+ });
100
+
101
+ describe('set', () => {
102
+ it('should set', () => {
103
+ const EXPIRES = 987654321;
104
+ const MOCK_NOW_TIMESTAMP = 123456789;
105
+ MockDate.set(MOCK_NOW_TIMESTAMP);
106
+ cache.set('test-key', { test: 'data' }, EXPIRES);
107
+ expect(mockEngine.set).toHaveBeenCalledWith(
108
+ 'test-key',
109
+ { test: 'data' },
110
+ MOCK_NOW_TIMESTAMP + EXPIRES
111
+ );
112
+ });
113
+ });
114
+
115
+ describe('remove', () => {
116
+ it('should remove', () => {
117
+ expect(mockEngine.remove).not.toHaveBeenCalled();
118
+ cache.remove('some-key');
119
+ expect(mockEngine.remove).toHaveBeenCalledWith('some-key');
120
+ });
121
+ });
122
+
123
+ describe('clear', () => {
124
+ it('should clear', () => {
125
+ expect(mockEngine.clear).not.toHaveBeenCalled();
126
+ cache.clear();
127
+ expect(mockEngine.clear).toHaveBeenCalled();
128
+ });
129
+ });
130
+ });
@@ -0,0 +1,48 @@
1
+ import { Static } from 'runtypes';
2
+ import { RuntypeBase } from 'runtypes/lib/runtype';
3
+ import log from '../utils/log';
4
+ import globalCache from './engines/global';
5
+ import { Engine } from './types';
6
+
7
+ let cacheEngine: Engine;
8
+
9
+ export const setCacheEngine = (engine: Engine) => {
10
+ cacheEngine = engine;
11
+ };
12
+
13
+ const getCacheEngine = (): Engine => cacheEngine || globalCache;
14
+
15
+ const set = (key: string, value: unknown, expires: number) =>
16
+ getCacheEngine().set(key, value, Date.now() + expires);
17
+
18
+ const remove = (key: string): Promise<void> => getCacheEngine().remove(key);
19
+
20
+ const get = async <T extends RuntypeBase>(
21
+ key: string,
22
+ validator: T
23
+ ): Promise<Static<T> | void> => {
24
+ const cacheEntry = await getCacheEngine().get(key);
25
+ if (!cacheEntry) {
26
+ return Promise.resolve();
27
+ }
28
+ if (Date.now() > cacheEntry.expires) {
29
+ remove(key);
30
+ return Promise.resolve();
31
+ }
32
+ try {
33
+ return validator.check(cacheEntry.data);
34
+ } catch (error) {
35
+ log.error(error, { cacheData: cacheEntry.data });
36
+ remove(key);
37
+ return Promise.resolve();
38
+ }
39
+ };
40
+
41
+ const clear = () => getCacheEngine().clear();
42
+
43
+ export default {
44
+ get,
45
+ set,
46
+ remove,
47
+ clear,
48
+ };
@@ -0,0 +1,12 @@
1
+ export type CacheEntry = {
2
+ key: string;
3
+ data: unknown;
4
+ expires: number;
5
+ };
6
+
7
+ export type Engine = {
8
+ get: (key: string) => Promise<CacheEntry | null>;
9
+ set: (key: string, data: unknown, expires: number) => Promise<void>;
10
+ remove: (key: string) => Promise<void>;
11
+ clear: () => Promise<void>;
12
+ };
@@ -0,0 +1,209 @@
1
+ import fetch from 'jest-fetch-mock';
2
+ import cache from '../cache';
3
+ import {
4
+ updateNamespace,
5
+ EuropaSchema,
6
+ clearLocalCache,
7
+ saveNamespace,
8
+ deleteNamespaceKey,
9
+ getNamespaces,
10
+ getAllNamespaces,
11
+ } from './europa';
12
+
13
+ beforeEach(() => {
14
+ cache.clear();
15
+ });
16
+
17
+ describe('Europa', () => {
18
+ it('saveNamespace should set namespace and return the new value', async () => {
19
+ const userInfo = { gender: 'U', post_code: 'U' };
20
+ fetch
21
+ .mockOnce(JSON.stringify(userInfo)) // data to save 'PUT'
22
+ .mockOnce(JSON.stringify({ namespaces: { user_info: userInfo } })); // data retrieved 'GET'
23
+
24
+ const namespaceData = await saveNamespace('user_info', userInfo);
25
+ expect(fetch).toHaveBeenCalledTimes(2);
26
+ expect(namespaceData).toMatchObject({ user_info: userInfo });
27
+ });
28
+
29
+ it('updateNamespace should update namespace', async () => {
30
+ const oldUserInfo = { gender: 'F', post_code: 'U' };
31
+ const newUserInfo = { gender: 'M', post_code: '2150' };
32
+
33
+ fetch.mockOnce(JSON.stringify({})); // initial response // 'PUT'
34
+ fetch.mockOnce(JSON.stringify({ namespaces: { user_info: oldUserInfo } })); // old 'GET'
35
+ fetch.mockOnce(JSON.stringify({ namespaces: { user_info: newUserInfo } })); // updated 'GET'
36
+
37
+ const old = await saveNamespace('user_info', oldUserInfo);
38
+ expect(fetch).toHaveBeenCalledTimes(2);
39
+ expect(old).toEqual({ user_info: oldUserInfo });
40
+
41
+ const updated = await updateNamespace('user_info', newUserInfo).then(() =>
42
+ cache.get('europa', EuropaSchema)
43
+ );
44
+ expect(updated).toMatchObject({ user_info: newUserInfo });
45
+ expect(fetch).toHaveBeenCalledTimes(3);
46
+ });
47
+
48
+ it('clearLocalCache should remove Europa cache', async () => {
49
+ fetch.mockResponse(JSON.stringify({ namespaces: { euucp: { x: 'x' } } }));
50
+
51
+ await saveNamespace('euucp', { x: 'x' });
52
+ expect(cache.get('europa', EuropaSchema)).resolves.toMatchObject({
53
+ euucp: { x: 'x' },
54
+ }); // expect something in cache
55
+
56
+ await clearLocalCache();
57
+ expect(cache.get('europa', EuropaSchema)).resolves.toBeUndefined(); // expect cache to be empty
58
+ });
59
+
60
+ it('deleteNamespaceKey should remove key from europa', async () => {
61
+ fetch
62
+ .mockOnce(JSON.stringify({})) // 'GET'
63
+ .mockOnce(JSON.stringify({ namespaces: { euucp: { x: 'x', y: 'y' } } })) // 'PUT'
64
+ .mockOnce(JSON.stringify({}), { status: 200 }) // 'DELETE'
65
+ .mockOnce(JSON.stringify({ namespaces: { euucp: { y: 'y' } } })); // 'PUT'
66
+
67
+ const data = { x: 'x', y: 'y' };
68
+
69
+ await saveNamespace('euucp', data);
70
+ // expect x and y
71
+ expect(await cache.get('europa', EuropaSchema)).toEqual(
72
+ expect.objectContaining({
73
+ euucp: data,
74
+ })
75
+ );
76
+
77
+ await deleteNamespaceKey('euucp', 'x');
78
+ // expect only y
79
+ expect(await cache.get('europa', EuropaSchema)).toEqual(
80
+ expect.objectContaining({
81
+ euucp: { y: 'y' },
82
+ })
83
+ );
84
+ });
85
+
86
+ it('getAllNamespaces should return all europa namespaces', async () => {
87
+ const data = {
88
+ euucp: { x: 'x' },
89
+ user_info: { gender: 'M', post_code: 'U' },
90
+ };
91
+
92
+ fetch.mockResponse(JSON.stringify({ namespaces: data }));
93
+ expect(await getAllNamespaces()).toMatchObject({ namespaces: data });
94
+ });
95
+ });
96
+
97
+ describe('getNamespaces', () => {
98
+ let response: any;
99
+ describe('with cold cache', () => {
100
+ describe('with one namespace', () => {
101
+ const data = { euucp: { x: 'x' } };
102
+ beforeEach(async () => {
103
+ fetch.mockResponse(JSON.stringify({ namespaces: data }));
104
+ response = await getNamespaces(['euucp']);
105
+ });
106
+ it('should return namespace', () => {
107
+ expect(response).toEqual(data);
108
+ });
109
+ });
110
+
111
+ describe('with multiple namespaces', () => {
112
+ const data = { euucp: { x: 'x' }, user_info: { a: 'a' } };
113
+ beforeEach(async () => {
114
+ fetch.mockResponse(JSON.stringify({ namespaces: data }));
115
+ response = await getNamespaces(['euucp', 'user_info']);
116
+ });
117
+ it('should return multiple namespaces', () => {
118
+ expect(response).toEqual(data);
119
+ });
120
+ });
121
+
122
+ describe('when doing sequence of calls for different namespaces', () => {
123
+ const data = { euucp: { x: 'x' } };
124
+ const data2 = { user_info: { a: 'a' } };
125
+ let response2: any;
126
+ beforeEach(async () => {
127
+ fetch.mockResponseOnce(JSON.stringify({ namespaces: data }));
128
+ fetch.mockResponseOnce(JSON.stringify({ namespaces: data2 }));
129
+ response = await getNamespaces(['euucp']);
130
+ response2 = await getNamespaces(['user_info']);
131
+ });
132
+ it('should return multiple namespaces', () => {
133
+ expect(response).toEqual(data);
134
+ expect(response2).toEqual(data2);
135
+ });
136
+ });
137
+
138
+ describe('when doing sequence of calls for different namespaces before first response returns', () => {
139
+ const data = { euucp: { x: 'x' } };
140
+ const data2 = { user_info: { a: 'a' } };
141
+ let response2: any;
142
+ beforeEach(async () => {
143
+ fetch.mockResponseOnce(
144
+ JSON.stringify({ namespaces: { ...data, ...data2 } })
145
+ );
146
+ const futureEuucp = getNamespaces(['euucp']);
147
+ response2 = await getNamespaces(['user_info']);
148
+ response = await futureEuucp;
149
+ });
150
+ it('should return euucp in first response', () => {
151
+ expect(response).toEqual(data);
152
+ });
153
+ it('should return user_info in second response', () => {
154
+ expect(response2).toEqual(data2);
155
+ });
156
+ });
157
+ });
158
+
159
+ describe('with one namespace in cache', () => {
160
+ const data = { euucp: { x: 'x' } };
161
+ beforeEach(() => {
162
+ cache.set('europa', data, 100000);
163
+ });
164
+
165
+ describe('when requesting cached namespace', () => {
166
+ beforeEach(async () => {
167
+ response = await getNamespaces(['euucp']);
168
+ });
169
+ it('should return namespace', () => {
170
+ expect(response).toEqual(data);
171
+ });
172
+ });
173
+
174
+ describe('when requesting namespace not found in cache', () => {
175
+ const expectedData = {
176
+ privacy_preferences: { allow_research_usage: true },
177
+ };
178
+
179
+ beforeEach(async () => {
180
+ fetch.mockResponse(JSON.stringify({ namespaces: expectedData }));
181
+ response = await getNamespaces(['privacy_preferences']);
182
+ });
183
+ it('should return namespace from backend, not from cache', () => {
184
+ expect(response).toEqual(expectedData);
185
+ });
186
+ });
187
+
188
+ describe('when requesting multiple namespaces and only one found in cache', () => {
189
+ const expectedData = {
190
+ privacy_preferences: { allow_research_usage: true },
191
+ euucp: { x: 'x' },
192
+ };
193
+
194
+ beforeEach(async () => {
195
+ fetch.mockResponse(JSON.stringify({ namespaces: expectedData }));
196
+ response = await getNamespaces(['privacy_preferences', 'euucp']);
197
+ });
198
+ it('should return namespace from backend, not from cache', () => {
199
+ expect(response).toEqual(expectedData);
200
+ });
201
+ });
202
+ });
203
+
204
+ it('should require at least one namespace', () => {
205
+ expect(getNamespaces([])).rejects.toThrowError(
206
+ new Error('namespaces array cannot be of length 0')
207
+ );
208
+ });
209
+ });
@@ -0,0 +1,183 @@
1
+ import { Unknown, Dictionary, String, Static } from 'runtypes';
2
+
3
+ import cache from '../cache';
4
+ import getOrUpdate from '../utils/getOrUpdate';
5
+ import log from '../utils/log';
6
+ import Debouncer from '../utils/debouncer';
7
+
8
+ const CACHE_DURATION = 5 * 60000; // 5 minutes
9
+ const DEBOUNCE_WAIT_TIME = 20; // 20ms wait before actually calling Europa
10
+
11
+ export const EuropaSchema = Dictionary(Unknown, String);
12
+
13
+ export const clearLocalCache = () => cache.remove('europa');
14
+
15
+ const doFetch = (url: string, method: string = 'GET', body?: Object) =>
16
+ fetch(url, {
17
+ method,
18
+ body: body && JSON.stringify(body),
19
+ headers: {
20
+ 'Content-Type': 'application/json',
21
+ Accept: 'application/json',
22
+ },
23
+ });
24
+
25
+ function mergeCache(
26
+ cachedData: Static<typeof EuropaSchema> | void,
27
+ newData: Static<typeof EuropaSchema>
28
+ ) {
29
+ return Object.entries(newData).reduce(
30
+ (mergedNamespaces, [namespace, data]) => ({
31
+ ...mergedNamespaces,
32
+ [namespace]: data,
33
+ }),
34
+ cachedData || {}
35
+ );
36
+ }
37
+
38
+ const updateNamespaceInCache = async (namespace: string, data: Object) => {
39
+ const cachedData = await cache.get('europa', EuropaSchema);
40
+ const updatedData = mergeCache(cachedData, { [namespace]: data });
41
+ return cache.set('europa', updatedData, Date.now() + CACHE_DURATION);
42
+ };
43
+
44
+ export const updateNamespace = async (namespace: string, data: Object) => {
45
+ const res = await doFetch(`/api/europa/v1/me/${namespace}`, 'PATCH', data);
46
+ if (!res.ok) {
47
+ log.error(
48
+ `Could not get namespace: ${namespace}, status: ${res.status}, statusText: ${res.statusText}`,
49
+ res
50
+ );
51
+ return {};
52
+ }
53
+ return updateNamespaceInCache(namespace, data);
54
+ };
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
+ if (response.status === 500 || response.status === 503) {
65
+ log.error(
66
+ `Could not get namespaces for: ${params}, status: ${response.status}`,
67
+ { response, body }
68
+ );
69
+ } else {
70
+ log.warn(
71
+ `Could not get namespaces for: ${params}, status: ${response.status}`,
72
+ { response, body }
73
+ );
74
+ }
75
+ return {};
76
+ }
77
+ return JSON.parse(body).namespaces;
78
+ })
79
+ );
80
+
81
+ export const getNamespaces = async <
82
+ S extends { [namespace: string]: { [index: string]: unknown } },
83
+ Namespaces extends Array<keyof S>
84
+ >(
85
+ namespaces: Namespaces,
86
+ options: { ignoreCache: boolean } = { ignoreCache: false }
87
+ ): Promise<Pick<S, Namespaces[number]>> => {
88
+ if (namespaces.length === 0) {
89
+ throw new Error('namespaces array cannot be of length 0');
90
+ }
91
+
92
+ let missingNamespaces = namespaces as string[];
93
+ const cachedData = (await cache.get('europa', EuropaSchema)) || {
94
+ namespaces: {},
95
+ };
96
+ if (!options.ignoreCache) {
97
+ missingNamespaces = (
98
+ cachedData
99
+ ? namespaces.filter(
100
+ (namespace) =>
101
+ !Object.keys(cachedData).includes(namespace as string)
102
+ )
103
+ : namespaces
104
+ ) as string[];
105
+ if (cachedData && missingNamespaces.length === 0) {
106
+ // Yay! Everything we need is in the cache!
107
+ return Promise.resolve(cachedData as Pick<S, Namespaces[number]>);
108
+ }
109
+ }
110
+
111
+ const fetchedNamespaces = await debouncer.perform(missingNamespaces);
112
+ Object.entries(fetchedNamespaces).forEach(([namespace, fetchedNamespace]) =>
113
+ updateNamespaceInCache(namespace, fetchedNamespace as Object)
114
+ );
115
+
116
+ return Promise.resolve(
117
+ // @ts-ignore
118
+ Object.entries(mergeCache(cachedData, fetchedNamespaces))
119
+ .filter(([namespace]) => namespaces.includes(namespace))
120
+ .reduce(
121
+ (returnedEntries, [namespace, data]) => ({
122
+ ...returnedEntries,
123
+ [namespace]: data,
124
+ }),
125
+ {} as Pick<S, Namespaces[number]>
126
+ )
127
+ );
128
+ };
129
+
130
+ export const saveNamespace = (namespace: string, data: Object) =>
131
+ doFetch(`/api/europa/v1/me/${namespace}`, 'PUT', data)
132
+ .then((res) => {
133
+ if (!res.ok) {
134
+ log.error(
135
+ `Could not get save namespace, namespace:${namespace} status: ${res.status}, statusText: ${res.statusText}`,
136
+ res
137
+ );
138
+ }
139
+ return {};
140
+ })
141
+ .then(() => getNamespaces([namespace], { ignoreCache: true })); // updates cache
142
+
143
+ export const getAllNamespaces = () =>
144
+ getOrUpdate(
145
+ 'europa',
146
+ EuropaSchema,
147
+ () =>
148
+ doFetch(`/api/europa/v1/me`)
149
+ .then((res) => {
150
+ if (!res.ok) {
151
+ log.error(
152
+ `Could not get all namespaces, status: ${res.status}, statusText: ${res.statusText}`,
153
+ res
154
+ );
155
+ return {};
156
+ }
157
+ return res.json();
158
+ })
159
+ .then((data) => {
160
+ const europaValidData = EuropaSchema.check(data);
161
+ try {
162
+ return {
163
+ ttl: CACHE_DURATION,
164
+ data: europaValidData,
165
+ };
166
+ } catch (error) {
167
+ log.error(error, { data });
168
+ throw error;
169
+ }
170
+ }),
171
+ () => false
172
+ );
173
+ export const deleteNamespaceKey = (namespace: string, key: string) =>
174
+ doFetch(`/api/europa/v1/me/${namespace}/${key}`, 'DELETE')
175
+ .then((res) => {
176
+ if (!res.ok) {
177
+ log.error(
178
+ `Could not get namespace: ${namespace}, status: ${res.status}, statusText: ${res.statusText}`,
179
+ res
180
+ );
181
+ }
182
+ })
183
+ .then(() => getNamespaces([namespace], { ignoreCache: true })); // updates cache