@amedia/user 0.13.35 → 0.13.37

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 (179) hide show
  1. package/dist/user.cjs +1 -1
  2. package/dist/user.cjs.map +3 -3
  3. package/dist/user.d.ts +15 -1
  4. package/dist/user.js +1 -1
  5. package/dist/user.js.map +3 -3
  6. package/package.json +5 -2
  7. package/.codeclimate.yml +0 -8
  8. package/.eslintignore +0 -2
  9. package/.eslintrc +0 -11
  10. package/.prettierrc.json +0 -1
  11. package/@types/amedia-frontend-rpc.d.ts +0 -11
  12. package/@types/browserid.d.ts +0 -4
  13. package/build.js +0 -28
  14. package/checkVersion.cjs +0 -12
  15. package/cloudbuild.json +0 -29
  16. package/cop.json +0 -8
  17. package/dist/actions/authentication.d.ts +0 -4
  18. package/dist/actions/authentication.spec.d.ts +0 -1
  19. package/dist/actions/authorization.d.ts +0 -14
  20. package/dist/actions/authorization.spec.d.ts +0 -4
  21. package/dist/actions/preferences.d.ts +0 -9
  22. package/dist/actions/preferences.spec.d.ts +0 -1
  23. package/dist/actions/storage.d.ts +0 -7
  24. package/dist/actions/userData.d.ts +0 -2
  25. package/dist/actions/userData.spec.d.ts +0 -1
  26. package/dist/autologin/index.d.ts +0 -7
  27. package/dist/autologin/index.spec.d.ts +0 -1
  28. package/dist/autologin/thirdPartyCookie.d.ts +0 -3
  29. package/dist/autologin/thirdPartyCookie.spec.d.ts +0 -1
  30. package/dist/cache/engines/global.d.ts +0 -24
  31. package/dist/cache/engines/global.spec.d.ts +0 -1
  32. package/dist/cache/index.d.ts +0 -11
  33. package/dist/cache/index.spec.d.ts +0 -1
  34. package/dist/cache/types.d.ts +0 -11
  35. package/dist/clients/europa.d.ts +0 -24
  36. package/dist/clients/europa.spec.d.ts +0 -1
  37. package/dist/clients/jupiter.d.ts +0 -30
  38. package/dist/clients/jupiter.spec.d.ts +0 -1
  39. package/dist/clients/mercury.d.ts +0 -3
  40. package/dist/clients/mercury.spec.d.ts +0 -1
  41. package/dist/clients/mercuryLog.d.ts +0 -8
  42. package/dist/clients/mercuryLog.spec.d.ts +0 -1
  43. package/dist/clients/nebula.d.ts +0 -2
  44. package/dist/clients/nebula.spec.d.ts +0 -1
  45. package/dist/clients/pluto.d.ts +0 -4
  46. package/dist/clients/pluto.spec.d.ts +0 -1
  47. package/dist/eventHandlers/activation.d.ts +0 -15
  48. package/dist/eventHandlers/authentication.d.ts +0 -17
  49. package/dist/eventHandlers/eventMap.d.ts +0 -29
  50. package/dist/eventHandlers/state.d.ts +0 -1
  51. package/dist/eventHandlers/state.spec.d.ts +0 -1
  52. package/dist/eventHandlers/storage.d.ts +0 -1
  53. package/dist/eventHandlers/storage.spec.d.ts +0 -1
  54. package/dist/eventHandlers/userAttributes.d.ts +0 -1
  55. package/dist/eventHandlers/userAttributes.spec.d.ts +0 -1
  56. package/dist/exceptions/PaywallError.d.ts +0 -8
  57. package/dist/index-authentcation.spec.d.ts +0 -1
  58. package/dist/index-storage.spec.d.ts +0 -1
  59. package/dist/index-subscription.spec.d.ts +0 -1
  60. package/dist/index.d.ts +0 -20
  61. package/dist/janitor/index.d.ts +0 -10
  62. package/dist/janitor/index.spec.d.ts +0 -1
  63. package/dist/janitor/jobs/accessCookieRefresher.d.ts +0 -1
  64. package/dist/janitor/jobs/accessCookieRefresher.spec.d.ts +0 -1
  65. package/dist/janitor/jobs/daxsubCookie.d.ts +0 -3
  66. package/dist/janitor/jobs/daxsubCookie.spec.d.ts +0 -1
  67. package/dist/janitor/jobs/removeUserStorage.d.ts +0 -1
  68. package/dist/janitor/jobs/removeUserStorage.spec.d.ts +0 -1
  69. package/dist/lib/PaywallUnlockRequest.d.ts +0 -17
  70. package/dist/lib/PaywallUnlockRequest.spec.d.ts +0 -1
  71. package/dist/lib/UserDataRequest.d.ts +0 -22
  72. package/dist/lib/UserDataRequest.spec.d.ts +0 -1
  73. package/dist/lib/cookie.d.ts +0 -9
  74. package/dist/lib/rpc.d.ts +0 -6
  75. package/dist/store/index.d.ts +0 -23
  76. package/dist/store/index.spec.d.ts +0 -1
  77. package/dist/types.d.ts +0 -22
  78. package/dist/utils/customEventWrapper.d.ts +0 -19
  79. package/dist/utils/debouncer.d.ts +0 -26
  80. package/dist/utils/debouncer.spec.d.ts +0 -1
  81. package/dist/utils/deepEquals.d.ts +0 -1
  82. package/dist/utils/expectBootLogs.d.ts +0 -2
  83. package/dist/utils/getOrUpdate.d.ts +0 -6
  84. package/dist/utils/getOrUpdate.spec.d.ts +0 -1
  85. package/dist/utils/localhostCheck.d.ts +0 -1
  86. package/dist/utils/location.d.ts +0 -3
  87. package/dist/utils/log.d.ts +0 -9
  88. package/dist/utils/log.spec.d.ts +0 -1
  89. package/dist/utils/loginState.d.ts +0 -2
  90. package/dist/utils/networkError.d.ts +0 -1
  91. package/dist/utils/queue.d.ts +0 -12
  92. package/dist/utils/type.d.ts +0 -6
  93. package/dist/utils/url.d.ts +0 -6
  94. package/dist/utils/url.spec.d.ts +0 -1
  95. package/eik.json +0 -10
  96. package/global.d.ts +0 -1
  97. package/jest.config.js +0 -7
  98. package/setupJest.js +0 -1
  99. package/src/actions/authentication.spec.ts +0 -51
  100. package/src/actions/authentication.ts +0 -43
  101. package/src/actions/authorization.spec.ts +0 -369
  102. package/src/actions/authorization.ts +0 -117
  103. package/src/actions/preferences.spec.ts +0 -41
  104. package/src/actions/preferences.ts +0 -41
  105. package/src/actions/storage.ts +0 -22
  106. package/src/actions/userData.spec.ts +0 -133
  107. package/src/actions/userData.ts +0 -68
  108. package/src/autologin/index.spec.ts +0 -239
  109. package/src/autologin/index.ts +0 -92
  110. package/src/autologin/thirdPartyCookie.spec.ts +0 -95
  111. package/src/autologin/thirdPartyCookie.ts +0 -55
  112. package/src/cache/engines/global.spec.ts +0 -62
  113. package/src/cache/engines/global.ts +0 -48
  114. package/src/cache/index.spec.ts +0 -130
  115. package/src/cache/index.ts +0 -48
  116. package/src/cache/types.ts +0 -12
  117. package/src/clients/europa.spec.ts +0 -209
  118. package/src/clients/europa.ts +0 -183
  119. package/src/clients/jupiter.spec.ts +0 -179
  120. package/src/clients/jupiter.ts +0 -119
  121. package/src/clients/mercury.spec.ts +0 -59
  122. package/src/clients/mercury.ts +0 -48
  123. package/src/clients/mercuryLog.spec.ts +0 -20
  124. package/src/clients/mercuryLog.ts +0 -67
  125. package/src/clients/nebula.spec.ts +0 -70
  126. package/src/clients/nebula.ts +0 -83
  127. package/src/clients/pluto.spec.ts +0 -165
  128. package/src/clients/pluto.ts +0 -118
  129. package/src/eventHandlers/activation.ts +0 -35
  130. package/src/eventHandlers/authentication.ts +0 -34
  131. package/src/eventHandlers/eventMap.ts +0 -34
  132. package/src/eventHandlers/state.spec.ts +0 -48
  133. package/src/eventHandlers/state.ts +0 -23
  134. package/src/eventHandlers/storage.spec.ts +0 -114
  135. package/src/eventHandlers/storage.ts +0 -45
  136. package/src/eventHandlers/userAttributes.spec.ts +0 -93
  137. package/src/eventHandlers/userAttributes.ts +0 -31
  138. package/src/exceptions/PaywallError.ts +0 -16
  139. package/src/index-authentcation.spec.ts +0 -26
  140. package/src/index-storage.spec.ts +0 -144
  141. package/src/index-subscription.spec.ts +0 -213
  142. package/src/index.ts +0 -59
  143. package/src/janitor/index.spec.ts +0 -18
  144. package/src/janitor/index.ts +0 -59
  145. package/src/janitor/jobs/accessCookieRefresher.spec.ts +0 -213
  146. package/src/janitor/jobs/accessCookieRefresher.ts +0 -98
  147. package/src/janitor/jobs/daxsubCookie.spec.ts +0 -109
  148. package/src/janitor/jobs/daxsubCookie.ts +0 -38
  149. package/src/janitor/jobs/removeUserStorage.spec.ts +0 -34
  150. package/src/janitor/jobs/removeUserStorage.ts +0 -12
  151. package/src/lib/PaywallUnlockRequest.spec.ts +0 -363
  152. package/src/lib/PaywallUnlockRequest.ts +0 -143
  153. package/src/lib/UserDataRequest.spec.ts +0 -77
  154. package/src/lib/UserDataRequest.ts +0 -213
  155. package/src/lib/cookie.ts +0 -121
  156. package/src/lib/rpc.ts +0 -19
  157. package/src/store/index.spec.ts +0 -49
  158. package/src/store/index.ts +0 -64
  159. package/src/types.ts +0 -22
  160. package/src/utils/customEventWrapper.ts +0 -58
  161. package/src/utils/debouncer.spec.ts +0 -252
  162. package/src/utils/debouncer.ts +0 -123
  163. package/src/utils/deepEquals.ts +0 -42
  164. package/src/utils/expectBootLogs.ts +0 -9
  165. package/src/utils/getOrUpdate.spec.ts +0 -166
  166. package/src/utils/getOrUpdate.ts +0 -66
  167. package/src/utils/localhostCheck.ts +0 -9
  168. package/src/utils/location.ts +0 -31
  169. package/src/utils/log.spec.ts +0 -148
  170. package/src/utils/log.ts +0 -124
  171. package/src/utils/loginState.ts +0 -24
  172. package/src/utils/networkError.ts +0 -11
  173. package/src/utils/queue.ts +0 -32
  174. package/src/utils/type.ts +0 -19
  175. package/src/utils/url.spec.ts +0 -33
  176. package/src/utils/url.ts +0 -35
  177. package/testSetup.js +0 -19
  178. package/tsconfig.eslint.json +0 -24
  179. package/tsconfig.json +0 -18
@@ -1,92 +0,0 @@
1
- import thirdPartyCookie from './thirdPartyCookie';
2
- import { getAidDomain, getCurrentUrl } from '../utils/url';
3
- import { navigateTo } from '../utils/location';
4
- import { getCookie, removeCookie, setCookie } from '../lib/cookie';
5
- import UserDataRequest from '../lib/UserDataRequest';
6
-
7
- export type Strategies = Array<{
8
- name: string;
9
- handler: () => Promise<boolean>;
10
- }>;
11
-
12
- const AUTOLOGIN_COOKIE = 'has-tried-autologin';
13
- export const AUTOLOGIN_COOKIE_TTL = 60000; // One minute
14
-
15
- function inIframe() {
16
- try {
17
- return window.self !== window.top;
18
- } catch (e) {
19
- return true;
20
- }
21
- }
22
-
23
- function hasAlreadyAttemptedAutoLogin() {
24
- const cookie = getCookie(AUTOLOGIN_COOKIE);
25
- if (cookie && typeof cookie !== 'object') {
26
- try {
27
- if (Date.now() - parseInt(cookie, 10) < AUTOLOGIN_COOKIE_TTL) {
28
- return true;
29
- }
30
- } catch (e) {
31
- removeCookie(AUTOLOGIN_COOKIE);
32
- }
33
- }
34
- setCookie(AUTOLOGIN_COOKIE, Date.now(), Date.now() + AUTOLOGIN_COOKIE_TTL);
35
- return false;
36
- }
37
-
38
- const attemptAutologin = async (strategies: Strategies) => {
39
- if (typeof window === 'undefined' || inIframe()) {
40
- // Avoid auto-login on preview for dr edition and in workers.
41
- return;
42
- }
43
-
44
- const {
45
- state: { isLoggedIn },
46
- } = await new UserDataRequest().fetch();
47
- if (isLoggedIn) {
48
- return;
49
- }
50
-
51
- // eslint-disable-next-line no-restricted-syntax
52
- for (const strategy of strategies) {
53
- // eslint-disable-next-line no-await-in-loop
54
- const shouldTryMoreStrategies = await strategy
55
- .handler()
56
- .then((shouldPerformAutoLogin) => {
57
- if (shouldPerformAutoLogin) {
58
- if (hasAlreadyAttemptedAutoLogin()) {
59
- return false;
60
- }
61
-
62
- // Try to get newspaper cookie
63
- const url = new URL(`https://${getAidDomain()}/aid/logg_inn/auto`);
64
- url.searchParams.set('context', `auto_login_${strategy.name}`);
65
- url.searchParams.set('requestedUrl', getCurrentUrl());
66
- navigateTo(url.href);
67
- return false;
68
- }
69
- return true;
70
- });
71
-
72
- if (!shouldTryMoreStrategies) {
73
- return;
74
- }
75
- }
76
- };
77
-
78
- export const attemptAutoLoginJob = async () =>
79
- attemptAutologin([
80
- {
81
- name: 'third_party',
82
- handler: thirdPartyCookie,
83
- },
84
- ]);
85
-
86
- export const attemptPaywallAutoLogin = async () =>
87
- attemptAutologin([
88
- {
89
- name: 'paywall',
90
- handler: () => Promise.resolve(true),
91
- },
92
- ]);
@@ -1,95 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import cache from '../cache';
3
- import thirdPartyCookie, { CACHE_KEY, CACHE_TTL } from './thirdPartyCookie';
4
- import * as location from '../utils/location';
5
- import * as url from '../utils/url';
6
-
7
- let shouldRedirectToAutoLogin = false;
8
-
9
- function itShouldSetAlreadyTriedCache() {
10
- it('should set already tried cache', () => {
11
- expect(cache.set).toHaveBeenCalledWith(CACHE_KEY, true, CACHE_TTL);
12
- });
13
- }
14
-
15
- function itShouldRedirectToAutoLogin() {
16
- it('should redirect to auto login', () => {
17
- expect(shouldRedirectToAutoLogin).toBeTruthy();
18
- });
19
- }
20
-
21
- function itShouldNotRedirectToAutoLogin() {
22
- it('should not redirect to auto login', () => {
23
- expect(shouldRedirectToAutoLogin).toBeFalsy();
24
- });
25
- }
26
-
27
- describe('Autologin: Third Party Cookie', () => {
28
- let cacheGetSpy: jasmine.Spy;
29
-
30
- beforeEach(() => {
31
- cacheGetSpy = spyOn(cache, 'get');
32
- spyOn(cache, 'set');
33
- spyOn(location, 'navigateTo');
34
- spyOn(url, 'getAidDomain').and.returnValue('www.aid.no');
35
- spyOn(url, 'getCurrentUrl').and.returnValue(
36
- 'https://avisnavn.no/abo/?query=param'
37
- );
38
- });
39
-
40
- describe('when not logged in first party', () => {
41
- describe('when already checked third party option', () => {
42
- beforeEach(async () => {
43
- cacheGetSpy.and.returnValue(true);
44
- shouldRedirectToAutoLogin = await thirdPartyCookie();
45
- });
46
-
47
- it('should not set already tried cache', () => {
48
- expect(cache.set).not.toHaveBeenCalled();
49
- });
50
- itShouldNotRedirectToAutoLogin();
51
- });
52
-
53
- describe('when not logged in via third party', () => {
54
- beforeEach(async () => {
55
- fetch.doMockIf(
56
- `https://www.aid.no/api/pluto/v1/sessions/current`,
57
- JSON.stringify({
58
- errors: [
59
- {
60
- id: 'xxx-000000000000',
61
- title: 'xxx',
62
- detail: 'xxx',
63
- status: '403',
64
- code: 'session.not_specified',
65
- },
66
- ],
67
- }),
68
- {
69
- status: 403,
70
- }
71
- );
72
- shouldRedirectToAutoLogin = await thirdPartyCookie();
73
- });
74
-
75
- itShouldSetAlreadyTriedCache();
76
- itShouldNotRedirectToAutoLogin();
77
- });
78
-
79
- describe('when logged in via third party', () => {
80
- beforeEach(async () => {
81
- fetch.doMockIf(
82
- `https://www.aid.no/api/pluto/v1/sessions/current`,
83
- JSON.stringify({
84
- user_name: 'Donald Duck',
85
- tracking_key: 'key',
86
- })
87
- );
88
- shouldRedirectToAutoLogin = await thirdPartyCookie();
89
- });
90
-
91
- itShouldSetAlreadyTriedCache();
92
- itShouldRedirectToAutoLogin();
93
- });
94
- });
95
- });
@@ -1,55 +0,0 @@
1
- import { Boolean, Record, Static, String } from 'runtypes';
2
- import cache from '../cache';
3
- import log from '../utils/log';
4
- import { getAidDomain } from '../utils/url';
5
- import { resolveBadPlutoResponse } from '../clients/pluto';
6
-
7
- export const CACHE_KEY = 'haveTriedThirdPartyLoginCheck';
8
- export const CACHE_TTL = 60 * 60 * 1000; // One hour
9
-
10
- const ServiceSessionSchema = Record({
11
- user_name: String,
12
- tracking_key: String,
13
- });
14
-
15
- const getAidSession = () =>
16
- <Promise<Static<typeof ServiceSessionSchema> | null>>fetch(
17
- `https://${getAidDomain()}/api/pluto/v1/sessions/current`,
18
- {
19
- mode: 'cors',
20
- credentials: 'include',
21
- }
22
- )
23
- .then((response) => {
24
- if (!response.ok) {
25
- return resolveBadPlutoResponse(response)
26
- .then(() => null)
27
- .catch(() => null);
28
- }
29
- return response.json();
30
- })
31
- .then((data) => {
32
- if (!data) {
33
- return null;
34
- }
35
- try {
36
- return ServiceSessionSchema.check(data);
37
- } catch (error) {
38
- log.error(error, { data });
39
- return null;
40
- }
41
- });
42
-
43
- export default async function thirdPartyCookie() {
44
- // TODO: Should perhaps use cookie for this? Cache as it stands now only survives on the current page until vi replace it with something more persistent
45
- if (await cache.get(CACHE_KEY, Boolean)) {
46
- return false;
47
- }
48
- await cache.set(CACHE_KEY, true, CACHE_TTL);
49
-
50
- const aidSession = await getAidSession();
51
- if (aidSession) {
52
- return true;
53
- }
54
- return false;
55
- }
@@ -1,62 +0,0 @@
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
- });
@@ -1,48 +0,0 @@
1
- import { CacheEntry, Engine } from '../types';
2
-
3
- declare global {
4
- // eslint-disable-next-line import/no-mutable-exports,no-var
5
- export var amediaUserCache: { [index: string]: CacheEntry };
6
-
7
- interface Window {
8
- amediaUserCache?: { [index: string]: CacheEntry };
9
- }
10
-
11
- namespace NodeJS {
12
- interface Global {
13
- amediaUserCache?: { [index: string]: CacheEntry };
14
- }
15
- }
16
- }
17
-
18
- const getStorage = () => {
19
- const rootObject = globalThis;
20
- // eslint-disable-next-line no-return-assign
21
- return rootObject.amediaUserCache || (rootObject.amediaUserCache = {});
22
- };
23
-
24
- export const get = (key: string): Promise<CacheEntry> => {
25
- const data = getStorage()[key];
26
- return Promise.resolve(data);
27
- };
28
-
29
- export const set = (
30
- key: string,
31
- data: unknown,
32
- expires: number
33
- ): Promise<void> => {
34
- getStorage()[key] = { key, data, expires };
35
- return Promise.resolve();
36
- };
37
-
38
- export const remove = (key: string): Promise<void> => {
39
- delete getStorage()[key];
40
- return Promise.resolve();
41
- };
42
-
43
- export const clear = (): Promise<void> => {
44
- globalThis.amediaUserCache = {};
45
- return Promise.resolve();
46
- };
47
-
48
- export default { get, set, remove, clear } as Engine;
@@ -1,130 +0,0 @@
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
- });
@@ -1,48 +0,0 @@
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
- };
@@ -1,12 +0,0 @@
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
- };