@amedia/user 0.5.3 → 0.6.0

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 (50) hide show
  1. package/README.md +2 -2
  2. package/cloudbuild.json +29 -0
  3. package/cop.json +8 -0
  4. package/dist/actions/authentication.d.ts +1 -1
  5. package/dist/actions/preferences.d.ts +9 -3
  6. package/dist/cache/index.d.ts +3 -2
  7. package/dist/clients/europa.d.ts +12 -0
  8. package/dist/clients/europa.spec.d.ts +1 -0
  9. package/dist/clients/jupiter.d.ts +29 -0
  10. package/dist/clients/jupiter.spec.d.ts +1 -0
  11. package/dist/clients/mercury.d.ts +18 -0
  12. package/dist/clients/mercury.spec.d.ts +4 -0
  13. package/dist/clients/nebula.d.ts +22 -0
  14. package/dist/clients/nebula.spec.d.ts +1 -0
  15. package/dist/clients/pluto.d.ts +8 -0
  16. package/dist/clients/pluto.spec.d.ts +1 -0
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +1 -1
  19. package/dist/lib/rpc.d.ts +6 -1
  20. package/dist/store/store.d.ts +13 -0
  21. package/dist/store/store.spec.d.ts +1 -0
  22. package/dist/types.d.ts +7 -0
  23. package/dist/utils/getOrUpdate.d.ts +3 -0
  24. package/package.json +4 -3
  25. package/src/actions/authentication.ts +2 -2
  26. package/src/actions/authorization.ts +4 -7
  27. package/src/actions/preferences.spec.ts +4 -5
  28. package/src/actions/preferences.ts +49 -47
  29. package/src/actions/userData.ts +2 -0
  30. package/src/cache/index.spec.ts +7 -2
  31. package/src/cache/index.ts +4 -3
  32. package/src/{services → clients}/europa.spec.ts +19 -20
  33. package/src/{services → clients}/europa.ts +3 -3
  34. package/src/{services → clients}/mercury.ts +0 -1
  35. package/src/index-authentcation.spec.ts +2 -2
  36. package/src/index-userdata.spec.ts +11 -11
  37. package/src/index.ts +4 -3
  38. package/src/lib/rpc.ts +9 -3
  39. package/src/store/store.spec.ts +34 -0
  40. package/src/store/store.ts +46 -0
  41. package/src/types.ts +8 -0
  42. package/src/utils/getOrUpdate.ts +41 -0
  43. package/src/utils/log.ts +2 -1
  44. /package/src/{services → clients}/jupiter.spec.ts +0 -0
  45. /package/src/{services → clients}/jupiter.ts +0 -0
  46. /package/src/{services → clients}/mercury.spec.ts +0 -0
  47. /package/src/{services → clients}/nebula.spec.ts +0 -0
  48. /package/src/{services → clients}/nebula.ts +0 -0
  49. /package/src/{services → clients}/pluto.spec.ts +0 -0
  50. /package/src/{services → clients}/pluto.ts +0 -0
package/dist/lib/rpc.d.ts CHANGED
@@ -1 +1,6 @@
1
- export declare const getRPCClient: () => any;
1
+ declare let rpcSessionClient: {
2
+ addMethod: (methodName: string) => void;
3
+ userAuthenticated: (boolean: any) => void;
4
+ };
5
+ export declare const getRPCClient: () => Pick<typeof rpcSessionClient, 'userAuthenticated'>;
6
+ export {};
@@ -0,0 +1,13 @@
1
+ import { State, UserAttributes } from '../types';
2
+ declare type StoreDataMap = {
3
+ userAttributes: UserAttributes;
4
+ state: State;
5
+ };
6
+ declare type Listener<T> = (data: T) => void;
7
+ declare const _default: {
8
+ set: (key: keyof StoreDataMap, value: UserAttributes | State) => void;
9
+ get: (key: keyof StoreDataMap) => UserAttributes | State | undefined;
10
+ on: (key: keyof StoreDataMap, listener: Listener<UserAttributes | State>) => void;
11
+ clear: () => void;
12
+ };
13
+ export default _default;
@@ -0,0 +1 @@
1
+ export {};
package/dist/types.d.ts CHANGED
@@ -5,6 +5,7 @@ export declare type UserAttributes = {
5
5
  trackingKey?: string;
6
6
  extraData?: [];
7
7
  access?: string[];
8
+ privacyPreferences?: PrivacyPreferences;
8
9
  };
9
10
  export declare type State = {
10
11
  isLoggedIn: boolean;
@@ -13,3 +14,9 @@ export declare type State = {
13
14
  export declare type AnonymousAttributes = {
14
15
  age: number;
15
16
  };
17
+ export declare type PrivacyPreferences = {
18
+ allowResearchUsage: Boolean;
19
+ connectWithSurveys: Boolean;
20
+ personalizedAds: Boolean;
21
+ personalizedContent: Boolean;
22
+ };
@@ -0,0 +1,3 @@
1
+ import { Runtype, Static } from 'runtypes';
2
+ declare const getOrUpdate: <T extends Runtype<unknown>>(key: string, schema: T, action: () => Promise<Static<T>>) => Promise<Static<T>>;
3
+ export default getOrUpdate;
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.5.3",
3
+ "version": "0.6.0",
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)",
7
7
  "main": "dist/index.js",
8
8
  "scripts": {
9
- "test": "jest",
10
- "lint": "eslint . --ext .ts",
9
+ "test": "jest --coverage",
10
+ "lint": "eslint ./src --ext .ts",
11
11
  "build": "webpack --mode=production"
12
12
  },
13
13
  "dependencies": {
@@ -35,6 +35,7 @@
35
35
  "eslint-plugin-prettier": "^3.4.0",
36
36
  "jest": "^26.6.3",
37
37
  "jest-fetch-mock": "^3.0.3",
38
+ "mockdate": "3.0.5",
38
39
  "npm-run-all": "4.1.5",
39
40
  "prettier": "2.2.1",
40
41
  "source-map-loader": "2.0.1",
@@ -3,7 +3,7 @@ import {
3
3
  InternalSessionSchema,
4
4
  removeSession,
5
5
  Session,
6
- } from '../services/pluto';
6
+ } from '../clients/pluto';
7
7
  import cache from '../cache';
8
8
  import { getRPCClient } from '../lib/rpc';
9
9
  import { removeCookie } from '../lib/cookie';
@@ -68,7 +68,7 @@ export const getSession = async (): Promise<Session | null> => {
68
68
 
69
69
  // Actually perform a request against backend for the session
70
70
  const session = await getCurrentSession();
71
- cache.set(IS_LOGGED_IN_CACHE_KEY, session, Date.now() + EXPIRES_10_SECONDS);
71
+ cache.set(IS_LOGGED_IN_CACHE_KEY, session, EXPIRES_10_SECONDS);
72
72
  isFetchingSession = false;
73
73
  return session;
74
74
  };
@@ -1,14 +1,11 @@
1
1
  import { Record, Array, String } from 'runtypes';
2
- import { checkForAccess } from '../services/jupiter';
2
+ import { checkForAccess } from '../clients/jupiter';
3
3
  import cache from '../cache';
4
4
  import queue from '../utils/queue';
5
5
  import log from '../utils/log';
6
6
  import { getCurrentPublicationDomain } from '../utils/url';
7
7
  import { UserAttributes } from '../types';
8
- import {
9
- activateSubscription,
10
- UserDeactivatedError,
11
- } from '../services/mercury';
8
+ import { activateSubscription, UserDeactivatedError } from '../clients/mercury';
12
9
  import { logout } from './authentication';
13
10
 
14
11
  const EXPIRES_OFFSET = 10000; // 10 seconds
@@ -19,7 +16,7 @@ const AccessSchema = Record({
19
16
  access: Array(String),
20
17
  });
21
18
 
22
- export const getAccess = async (): Promise<Pick<UserAttributes, 'access'>> =>
19
+ export const getAccess = (): Promise<Pick<UserAttributes, 'access'>> =>
23
20
  new Promise((resolve, reject) => {
24
21
  queue.add(GET_ACCESS_QUEUE_KEY, { resolve, reject });
25
22
  if (queue.peekQueueSize(GET_ACCESS_QUEUE_KEY) > 1) {
@@ -38,7 +35,7 @@ export const getAccess = async (): Promise<Pick<UserAttributes, 'access'>> =>
38
35
  cache.set(
39
36
  GET_ACCESS_CACHE_KEY,
40
37
  accessState.access_features,
41
- Date.now() + EXPIRES_OFFSET
38
+ EXPIRES_OFFSET
42
39
  );
43
40
  queue.getAll(GET_ACCESS_QUEUE_KEY).forEach((promise) => {
44
41
  promise.resolve({ access: accessState.access_features });
@@ -1,7 +1,7 @@
1
1
  import fetch from 'jest-fetch-mock';
2
2
  import cache from '../cache';
3
3
  import queue from '../utils/queue';
4
- import privacyPreferences from './preferences';
4
+ import { getPrivacyPreferences } from './preferences';
5
5
 
6
6
  fetch.enableMocks();
7
7
 
@@ -24,7 +24,7 @@ const europaResponse = {
24
24
  describe('privacyPreferences', () => {
25
25
  it('should return preferences', async () => {
26
26
  fetch.mockResponse(JSON.stringify(europaResponse));
27
- await privacyPreferences();
27
+ await getPrivacyPreferences();
28
28
  expect(fetch).toHaveBeenCalledTimes(1);
29
29
  });
30
30
 
@@ -32,8 +32,7 @@ describe('privacyPreferences', () => {
32
32
  fetch.mockResponse(JSON.stringify(europaResponse));
33
33
 
34
34
  jest.spyOn(queue, 'add');
35
- privacyPreferences();
36
- await privacyPreferences();
35
+ await Promise.all([getPrivacyPreferences(), getPrivacyPreferences()]);
37
36
  expect(queue.add).toHaveBeenCalledTimes(2);
38
37
  expect(fetch).toHaveBeenCalledTimes(1);
39
38
  });
@@ -49,7 +48,7 @@ describe('privacyPreferences', () => {
49
48
  personalizedContent: false,
50
49
  })
51
50
  );
52
- await Promise.all([privacyPreferences(), privacyPreferences()]);
51
+ await Promise.all([getPrivacyPreferences(), getPrivacyPreferences()]);
53
52
  expect(fetch).toHaveBeenCalledTimes(0);
54
53
  });
55
54
  });
@@ -1,67 +1,69 @@
1
- import { Record, Boolean, Static } from 'runtypes';
1
+ import { Record, Boolean } from 'runtypes';
2
2
  import cache from '../cache';
3
- import { getNamespace } from '../services/europa';
3
+ import { getNamespace } from '../clients/europa';
4
+ import { UserAttributes, PrivacyPreferences } from '../types';
4
5
  import log from '../utils/log';
5
6
  import queue from '../utils/queue';
6
7
 
7
8
  const CACHE_DURATION = 5 * 60000; // 5 minutes
8
- const PRIVACY_PREFERENCES_QUEUE = 'privacy_preferences_queue';
9
+ const PRIVACY_PREFERENCES_QUEUE_KEY = 'privacy_preferences_queue';
10
+ const PRIVACY_PREFERENCES_CACHE_KEY = 'privacyPreferences';
9
11
 
10
- const PrivacyPreferencesSchema = Record({
12
+ export const PrivacyPreferencesSchema = Record({
11
13
  allowResearchUsage: Boolean,
12
14
  connectWithSurveys: Boolean,
13
15
  personalizedAds: Boolean,
14
16
  personalizedContent: Boolean,
15
17
  });
16
18
 
17
- type PrivacyPreferences = Static<typeof PrivacyPreferencesSchema>;
18
-
19
19
  const toBoolean = (val: string | boolean) => val === 'true' || val === true;
20
20
 
21
- let isCallingPrivacyPreferences: boolean;
22
- export const setIsCallingPrivacyPreferences = (value: boolean) =>
23
- (isCallingPrivacyPreferences = value);
24
-
25
- const privacyPreferences = () => {
26
- return new Promise(async (resolve, reject) => {
27
- queue.add(PRIVACY_PREFERENCES_QUEUE, { resolve, reject });
28
- if (queue.peekQueueSize(PRIVACY_PREFERENCES_QUEUE) > 1) {
29
- return;
30
- }
31
-
32
- const cachedData = await cache.get(
33
- 'privacyPreferences',
34
- PrivacyPreferencesSchema
35
- );
36
- if (cachedData) {
37
- queue.getAll(PRIVACY_PREFERENCES_QUEUE).forEach((promise) => {
38
- promise.resolve(cachedData);
39
- });
21
+ export const getPrivacyPreferences = async (): Promise<UserAttributes> =>
22
+ new Promise((resolve, reject) => {
23
+ queue.add(PRIVACY_PREFERENCES_QUEUE_KEY, { resolve, reject });
24
+ if (queue.peekQueueSize(PRIVACY_PREFERENCES_QUEUE_KEY) > 1) {
40
25
  return;
41
26
  }
42
27
 
43
- let europaData: any;
44
- try {
45
- europaData = await getNamespace('privacy_preferences');
46
- } catch (error) {
47
- log.error(`Could not fetch europaData`, error);
48
- queue.getAll(PRIVACY_PREFERENCES_QUEUE).forEach((promise) => {
49
- promise.reject();
50
- });
51
- }
28
+ cache
29
+ .get(PRIVACY_PREFERENCES_CACHE_KEY, PrivacyPreferencesSchema)
30
+ .then((cacheResponse) => {
31
+ if (cacheResponse) {
32
+ queue.getAll(PRIVACY_PREFERENCES_QUEUE_KEY).forEach((promise) => {
33
+ promise.resolve({ privacyPreferences: cacheResponse });
34
+ });
35
+ return;
36
+ }
52
37
 
53
- const mappedPrivacy: PrivacyPreferences = {
54
- allowResearchUsage: toBoolean(europaData.allow_research_usage),
55
- connectWithSurveys: toBoolean(europaData.connect_with_surveys),
56
- personalizedAds: toBoolean(europaData.personalized_ads),
57
- personalizedContent: toBoolean(europaData.personalized_content),
58
- };
38
+ const namespace = 'privacy_preferences';
39
+ getNamespace(namespace)
40
+ .then((namespaceData) => {
41
+ const mappedPrivacy: PrivacyPreferences = {
42
+ allowResearchUsage: toBoolean(namespaceData.allow_research_usage),
43
+ connectWithSurveys: toBoolean(namespaceData.connect_with_surveys),
44
+ personalizedAds: toBoolean(namespaceData.personalized_ads),
45
+ personalizedContent: toBoolean(
46
+ namespaceData.personalized_content
47
+ ),
48
+ };
59
49
 
60
- cache.set('privacyPreferences', mappedPrivacy, Date.now() + CACHE_DURATION);
61
- queue.getAll(PRIVACY_PREFERENCES_QUEUE).forEach((promise) => {
62
- promise.resolve(mappedPrivacy);
63
- });
50
+ cache.set(
51
+ PRIVACY_PREFERENCES_CACHE_KEY,
52
+ mappedPrivacy,
53
+ CACHE_DURATION
54
+ );
55
+ queue.getAll(PRIVACY_PREFERENCES_QUEUE_KEY).forEach((promise) => {
56
+ promise.resolve({ privacyPreferences: mappedPrivacy });
57
+ });
58
+ })
59
+ .catch((error) => {
60
+ log.error(
61
+ `Could not fetch data for namespace: ${namespace}`,
62
+ error
63
+ );
64
+ queue.getAll(PRIVACY_PREFERENCES_QUEUE_KEY).forEach((promise) => {
65
+ promise.reject();
66
+ });
67
+ });
68
+ });
64
69
  });
65
- };
66
-
67
- export default privacyPreferences;
@@ -2,6 +2,7 @@ import log from '../utils/log';
2
2
  import { UserAttributes } from '../types';
3
3
  import { getSession } from './authentication';
4
4
  import { getAccess } from './authorization';
5
+ import { getPrivacyPreferences } from './preferences';
5
6
 
6
7
  // TODO We may want actions to tell us what they can deliver and not have this "organizer" (wohoo-bad-name) tell the actions..
7
8
  const dataServiceMap: {
@@ -13,6 +14,7 @@ const dataServiceMap: {
13
14
  // @ts-ignore
14
15
  trackingKey: getSession,
15
16
  access: getAccess,
17
+ privacyPreferences: getPrivacyPreferences,
16
18
  };
17
19
 
18
20
  let currentUserData: UserAttributes = {};
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import { Record, String } from 'runtypes';
6
+ import * as MockDate from 'mockdate';
6
7
  import cache, { setCacheEngine } from '.';
7
8
  import log from '../utils/log';
8
9
  import resetAllMocks = jest.resetAllMocks;
@@ -14,6 +15,7 @@ const TestDataSchema = Record({
14
15
  let mockEngine;
15
16
  beforeEach(() => {
16
17
  resetAllMocks();
18
+ MockDate.reset();
17
19
  // @ts-ignore
18
20
  mockEngine = {
19
21
  get: jest.fn(),
@@ -86,11 +88,14 @@ describe('Cache', () => {
86
88
 
87
89
  describe('set', () => {
88
90
  it('should set', () => {
89
- cache.set('test-key', { test: 'data' }, 1234567890);
91
+ const EXPIRES = 987654321;
92
+ const MOCK_NOW_TIMESTAMP = 123456789;
93
+ MockDate.set(MOCK_NOW_TIMESTAMP);
94
+ cache.set('test-key', { test: 'data' }, EXPIRES);
90
95
  expect(mockEngine.set).toHaveBeenCalledWith(
91
96
  'test-key',
92
97
  { test: 'data' },
93
- 1234567890
98
+ MOCK_NOW_TIMESTAMP + EXPIRES
94
99
  );
95
100
  });
96
101
  });
@@ -1,4 +1,5 @@
1
- import { Record, Static, ValidationError } from 'runtypes';
1
+ import { Static, ValidationError } from 'runtypes';
2
+ import { RuntypeBase } from 'runtypes/lib/runtype';
2
3
  import globalCache from './engines/global';
3
4
  import { Engine } from './types';
4
5
  import log from '../utils/log';
@@ -12,11 +13,11 @@ export const setCacheEngine = (engine: Engine) => {
12
13
  const getCacheEngine = (): Engine => cacheEngine || globalCache;
13
14
 
14
15
  const set = (key: string, value: unknown, expires: number) =>
15
- getCacheEngine().set(key, value, expires);
16
+ getCacheEngine().set(key, value, Date.now() + expires);
16
17
 
17
18
  const remove = (key: string): Promise<void> => getCacheEngine().remove(key);
18
19
 
19
- const get = async <T extends Record<any, any>>(
20
+ const get = async <T extends RuntypeBase>(
20
21
  key: string,
21
22
  validator: T
22
23
  ): Promise<Static<T> | void> => {
@@ -39,8 +39,8 @@ describe('Europa', () => {
39
39
  expect(fetch).toHaveBeenCalledTimes(2);
40
40
  expect(old).toMatchObject(oldUserInfo);
41
41
 
42
- const updated = await updateNamespace('user_info', newUserInfo).then(
43
- async () => await cache.get('europa', EuropaSchema)
42
+ const updated = await updateNamespace('user_info', newUserInfo).then(() =>
43
+ cache.get('europa', EuropaSchema)
44
44
  );
45
45
  expect(updated).toMatchObject({ namespaces: { user_info: newUserInfo } });
46
46
  expect(fetch).toHaveBeenCalledTimes(3);
@@ -50,45 +50,44 @@ describe('Europa', () => {
50
50
  fetch.mockResponse(JSON.stringify({ namespaces: { euucp: { x: 'x' } } }));
51
51
 
52
52
  await saveNamespace('euucp', { x: 'x' });
53
- const x = await cache.get('europa', EuropaSchema);
54
- expect(x).toMatchObject({ namespaces: { euucp: { x: 'x' } } }); // expect something in cache
53
+ expect(cache.get('europa', EuropaSchema)).resolves.toMatchObject({
54
+ namespaces: { euucp: { x: 'x' } },
55
+ }); // expect something in cache
55
56
 
56
57
  await clearLocalCache();
57
- expect(await cache.get('europa', EuropaSchema)).toBeUndefined; // expect cache to be empty
58
+ expect(cache.get('europa', EuropaSchema)).resolves.toBeUndefined(); // expect cache to be empty
58
59
  });
59
60
 
60
61
  it('deleteNamespaceKey should remove key from europa', async () => {
61
- fetch.mockOnce(JSON.stringify({})); // 'GET'
62
- fetch.mockOnce(
63
- JSON.stringify({ namespaces: { euucp: { x: 'x', y: 'y' } } })
64
- ); // 'PUT'
65
- fetch.mockOnce(JSON.stringify({}), { status: 200 }); // 'DELETE'
66
- fetch.mockOnce(JSON.stringify({ namespaces: { euucp: { y: 'y' } } })); // 'PUT'
62
+ fetch
63
+ .mockOnce(JSON.stringify({})) // 'GET'
64
+ .mockOnce(JSON.stringify({ namespaces: { euucp: { x: 'x', y: 'y' } } })) // 'PUT'
65
+ .mockOnce(JSON.stringify({}), { status: 200 }) // 'DELETE'
66
+ .mockOnce(JSON.stringify({ namespaces: { euucp: { y: 'y' } } })); // 'PUT'
67
67
 
68
68
  await saveNamespace('euucp', { x: 'x' });
69
- const beforeDelete = await cache.get('europa', EuropaSchema);
70
- expect(beforeDelete).toMatchObject({
69
+ expect(cache.get('europa', EuropaSchema)).resolves.toMatchObject({
71
70
  namespaces: { euucp: { x: 'x', y: 'y' } },
72
71
  }); // expect x and y
73
72
 
74
73
  await deleteNamespaceKey('euucp', 'x');
75
- const afterDelete = await cache.get('europa', EuropaSchema);
76
- expect(afterDelete).toMatchObject({ namespaces: { euucp: { y: 'y' } } }); // expect only y
74
+ expect(cache.get('europa', EuropaSchema)).resolves.toMatchObject({
75
+ namespaces: { euucp: { y: 'y' } },
76
+ }); // expect only y
77
77
  });
78
78
 
79
- it('getAllNamespaces should return all europa namespaces', async () => {
79
+ it('getAllNamespaces should return all europa namespaces', () => {
80
80
  const namespaceData = {
81
81
  euucp: { x: 'x' },
82
82
  user_info: { gender: 'M', post_code: 'U' },
83
83
  };
84
84
 
85
85
  fetch.mockResponse(JSON.stringify({ namespaces: namespaceData }));
86
- const retrieved = await getAllNamespaces();
87
- expect(retrieved).toMatchObject(namespaceData);
86
+ expect(getAllNamespaces()).resolves.toMatchObject(namespaceData);
88
87
  });
89
88
 
90
- it('getNamespace should return europa namespace', async () => {
89
+ it('getNamespace should return europa namespace', () => {
91
90
  fetch.mockResponse(JSON.stringify({ namespaces: { euucp: { x: 'x' } } }));
92
- expect(await getNamespace('euucp')).toMatchObject({ x: 'x' });
91
+ expect(getNamespace('euucp')).resolves.toMatchObject({ x: 'x' });
93
92
  });
94
93
  });
@@ -46,7 +46,7 @@ export const updateNamespace = async (namespace: string, data: Object) => {
46
46
  );
47
47
  return {};
48
48
  }
49
- return await updateNamespaceInCache(namespace, data);
49
+ return updateNamespaceInCache(namespace, data);
50
50
  };
51
51
 
52
52
  export const getNamespace = async (
@@ -90,8 +90,8 @@ export const saveNamespace = (namespace: string, data: Object) =>
90
90
  `Could not get save namespace, namespace:${namespace} status: ${res.status}, statusText: ${res.statusText}`,
91
91
  res
92
92
  );
93
- return {};
94
93
  }
94
+ return {};
95
95
  })
96
96
  .then(() => getNamespace(namespace, { ignoreCache: true })); // updates cache
97
97
 
@@ -109,7 +109,7 @@ export const getAllNamespaces = () =>
109
109
  })
110
110
  .then((data) => {
111
111
  const europaValidData = EuropaSchema.check(data);
112
- cache.set('europa', europaValidData, Date.now() + CACHE_DURATION);
112
+ cache.set('europa', europaValidData, CACHE_DURATION);
113
113
  return europaValidData.namespaces;
114
114
  });
115
115
 
@@ -66,7 +66,6 @@ export const activateSubscription = async (
66
66
  }
67
67
  return false;
68
68
  }
69
- console.log(data);
70
69
  return data?.status === 'success' && data?.access === 'granted';
71
70
  });
72
71
 
@@ -2,7 +2,7 @@
2
2
  * @jest-environment jsdom
3
3
  */
4
4
 
5
- import { login, logout } from './index';
5
+ 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';
@@ -31,7 +31,7 @@ describe('Public endpoint - authentication', () => {
31
31
 
32
32
  it('should login', () => {
33
33
  jest.spyOn(authentication, 'login').mockImplementation();
34
- login('https://www.avisnavn.no');
34
+ goToLoginPage('https://www.avisnavn.no');
35
35
  expect(authentication.login).toHaveBeenCalledWith(
36
36
  'https://www.avisnavn.no'
37
37
  );
@@ -2,7 +2,7 @@
2
2
  * @jest-environment jsdom
3
3
  */
4
4
 
5
- import { subscribeToUserUpdates } from './index';
5
+ import { subscribeToUserAttributes } from './index';
6
6
  import * as userData from './actions/userData';
7
7
  import { setRootElement } from './utils/customEventWrapper';
8
8
  import { listenForUserAttributeRequests } from './eventHandlers/userAttributes';
@@ -30,7 +30,7 @@ describe('Public endpoint - userdata', () => {
30
30
  });
31
31
 
32
32
  const onUserUpdate = jest.fn();
33
- subscribeToUserUpdates(['name'], onUserUpdate);
33
+ subscribeToUserAttributes(['name'], onUserUpdate);
34
34
 
35
35
  expect(onUserUpdate).toHaveBeenCalledWith({
36
36
  name: 'Donald Duck',
@@ -47,9 +47,9 @@ describe('Public endpoint - userdata', () => {
47
47
  });
48
48
 
49
49
  const onUserUpdate1 = jest.fn();
50
- subscribeToUserUpdates(['name'], onUserUpdate1);
50
+ subscribeToUserAttributes(['name'], onUserUpdate1);
51
51
  const onUserUpdate2 = jest.fn();
52
- subscribeToUserUpdates(['name'], onUserUpdate2);
52
+ subscribeToUserAttributes(['name'], onUserUpdate2);
53
53
 
54
54
  expect(onUserUpdate1).toHaveBeenCalledTimes(1);
55
55
  expect(onUserUpdate1).toHaveBeenCalledWith({
@@ -77,10 +77,10 @@ describe('Public endpoint - userdata', () => {
77
77
  });
78
78
 
79
79
  const firstOnUserUpdate = jest.fn();
80
- subscribeToUserUpdates(['name'], firstOnUserUpdate);
80
+ subscribeToUserAttributes(['name'], firstOnUserUpdate);
81
81
 
82
82
  const secondOnUserUpdate = jest.fn();
83
- subscribeToUserUpdates(['name'], secondOnUserUpdate);
83
+ subscribeToUserAttributes(['name'], secondOnUserUpdate);
84
84
 
85
85
  expect(firstOnUserUpdate).toHaveBeenCalledTimes(2);
86
86
  expect(firstOnUserUpdate).nthCalledWith(1, {});
@@ -105,7 +105,7 @@ describe('Public endpoint - userdata', () => {
105
105
  });
106
106
 
107
107
  const onUserUpdate = jest.fn();
108
- subscribeToUserUpdates(['name'], onUserUpdate);
108
+ subscribeToUserAttributes(['name'], onUserUpdate);
109
109
 
110
110
  expect(onUserUpdate).toHaveBeenCalledWith({
111
111
  name: 'Donald Duck',
@@ -124,7 +124,7 @@ describe('Public endpoint - userdata', () => {
124
124
  });
125
125
 
126
126
  const onUserUpdate = jest.fn();
127
- subscribeToUserUpdates(['name', 'email'], onUserUpdate);
127
+ subscribeToUserAttributes(['name', 'email'], onUserUpdate);
128
128
 
129
129
  expect(onUserUpdate).toHaveBeenCalledWith({
130
130
  name: 'Donald Duck',
@@ -143,7 +143,7 @@ describe('Public endpoint - userdata', () => {
143
143
  });
144
144
 
145
145
  const onUserUpdate = jest.fn();
146
- expect(() => subscribeToUserUpdates([], onUserUpdate)).toThrowError(
146
+ expect(() => subscribeToUserAttributes([], onUserUpdate)).toThrowError(
147
147
  new Error('You must subscribe to at least one attribute')
148
148
  );
149
149
  });
@@ -159,10 +159,10 @@ describe('Public endpoint - userdata', () => {
159
159
  });
160
160
 
161
161
  const firstOnUserUpdate = jest.fn();
162
- subscribeToUserUpdates(['name', 'email'], firstOnUserUpdate);
162
+ subscribeToUserAttributes(['name', 'email'], firstOnUserUpdate);
163
163
 
164
164
  const secondOnUserUpdate = jest.fn();
165
- subscribeToUserUpdates(['email'], secondOnUserUpdate);
165
+ subscribeToUserAttributes(['email'], secondOnUserUpdate);
166
166
 
167
167
  expect(firstOnUserUpdate).toHaveBeenCalledTimes(1);
168
168
  expect(firstOnUserUpdate).nthCalledWith(1, {
package/src/index.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import 'regenerator-runtime';
2
2
  import _ from 'lodash';
3
- import { AuthenticationEvents } from './eventHandlers/authentication';
4
3
  import { AmediaUserEvents } from './eventHandlers/userAttributes';
5
4
  import { ActivationEvents } from './eventHandlers/activation';
6
5
  import { dispatch, listenForAllEvents } from './utils/customEventWrapper';
@@ -11,7 +10,9 @@ import * as authentication from './actions/authentication';
11
10
  * Enables you to subscribe to the user attributes you care about and
12
11
  * get notified when something changes
13
12
  */
14
- export const subscribeToUserUpdates = <T extends Array<keyof UserAttributes>>(
13
+ export const subscribeToUserAttributes = <
14
+ T extends Array<keyof UserAttributes>
15
+ >(
15
16
  attributes: T,
16
17
  onUserUpdated: (attributes: Pick<UserAttributes, T[number]>) => void,
17
18
  onStateUpdated?: (attributes: State) => void
@@ -56,7 +57,7 @@ export const subscribeToUserUpdates = <T extends Array<keyof UserAttributes>>(
56
57
  * to the requestedUrl if supplied or the current url before redirecting away if not.
57
58
  * @param requestedUrl
58
59
  */
59
- export const login = (requestedUrl?: string) =>
60
+ export const goToLoginPage = (requestedUrl?: string) =>
60
61
  authentication.login(requestedUrl || window.location.href);
61
62
  export const logout = () => authentication.logout();
62
63
  export const tryActivateSubscriptionAccess = (
package/src/lib/rpc.ts CHANGED
@@ -1,15 +1,21 @@
1
1
  import { RPCclient } from '@amedia/frontend-rpc';
2
2
 
3
- let rpcSessionClient;
4
- export const getRPCClient = () => {
3
+ let rpcSessionClient: {
4
+ addMethod: (methodName: string) => void;
5
+ userAuthenticated: (boolean) => void;
6
+ };
7
+ export const getRPCClient = (): Pick<
8
+ typeof rpcSessionClient,
9
+ 'userAuthenticated'
10
+ > => {
5
11
  if (rpcSessionClient) {
6
12
  return rpcSessionClient;
7
13
  }
8
14
  rpcSessionClient = new RPCclient({
9
15
  version: '1.0.0',
10
16
  component: `userdata-session`,
17
+ methods: ['userAuthenticated'],
11
18
  });
12
19
 
13
- rpcSessionClient.addMethod('userAuthenticated');
14
20
  return rpcSessionClient;
15
21
  };
@@ -0,0 +1,34 @@
1
+ import store from './store';
2
+
3
+ beforeEach(() => {
4
+ store.clear();
5
+ });
6
+
7
+ describe('State', () => {
8
+ it('should set in state', () => {
9
+ store.set('userAttributes', { access: ['newspaper'] });
10
+ expect(store.get('userAttributes')).toEqual({ access: ['newspaper'] });
11
+ });
12
+
13
+ it('should emit on change', () => {
14
+ const listenerSpy = jest.fn();
15
+ store.on('userAttributes', listenerSpy);
16
+ expect(listenerSpy).not.toHaveBeenCalled();
17
+ store.set('userAttributes', { name: 'Donald' });
18
+ expect(listenerSpy).toHaveBeenCalledWith({ name: 'Donald' });
19
+ });
20
+
21
+ it('should emit to multiple relevant', () => {
22
+ const listenerSpy1 = jest.fn();
23
+ const listenerSpy2 = jest.fn();
24
+ const listenerSpy3 = jest.fn();
25
+ store.on('userAttributes', listenerSpy1);
26
+ store.on('userAttributes', listenerSpy2);
27
+ store.on('state', listenerSpy3);
28
+
29
+ store.set('userAttributes', { name: 'Donald' });
30
+ expect(listenerSpy1).toHaveBeenCalledWith({ name: 'Donald' });
31
+ expect(listenerSpy2).toHaveBeenCalledWith({ name: 'Donald' });
32
+ expect(listenerSpy3).not.toHaveBeenCalled();
33
+ });
34
+ });