@amedia/user 0.7.3 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/index.d.ts +6 -17
  2. package/dist/index.js +7 -2
  3. package/dist/lib/authentication.d.ts +17 -0
  4. package/dist/lib/authentication.js +74 -0
  5. package/dist/lib/authorization.d.ts +14 -0
  6. package/dist/lib/authorization.js +51 -0
  7. package/dist/{cache/engines/indexeddb.d.ts → lib/cache/db.d.ts} +2 -3
  8. package/dist/lib/cache/db.js +13 -0
  9. package/dist/lib/cache/global.d.ts +9 -0
  10. package/dist/lib/cache/global.js +16 -0
  11. package/dist/lib/cache/types.d.ts +5 -0
  12. package/dist/lib/cache/types.js +2 -0
  13. package/dist/lib/queue.d.ts +5 -0
  14. package/dist/lib/queue.js +17 -0
  15. package/dist/lib/tools.d.ts +1 -0
  16. package/dist/lib/tools.js +2 -0
  17. package/dist/lib/user.d.ts +2 -0
  18. package/dist/lib/user.js +3 -0
  19. package/dist/services/cache.d.ts +9 -0
  20. package/dist/services/cache.js +34 -0
  21. package/dist/{clients → services}/jupiter.d.ts +5 -6
  22. package/dist/services/jupiter.js +72 -0
  23. package/dist/services/pluto.d.ts +12 -0
  24. package/dist/services/pluto.js +40 -0
  25. package/package.json +1 -1
  26. package/src/actions/authorization.ts +2 -2
  27. package/src/actions/preferences.spec.ts +1 -3
  28. package/src/cache/index.spec.ts +2 -2
  29. package/src/clients/europa.spec.ts +0 -2
  30. package/src/clients/jupiter.spec.ts +26 -0
  31. package/src/clients/jupiter.ts +3 -2
  32. package/src/clients/mercury.spec.ts +5 -7
  33. package/src/clients/mercury.ts +4 -2
  34. package/src/clients/pluto.spec.ts +0 -2
  35. package/src/eventHandlers/activation.ts +2 -2
  36. package/src/index-authentcation.spec.ts +2 -1
  37. package/src/index-subscription.spec.ts +20 -13
  38. package/src/index.ts +58 -34
  39. package/src/utils/getOrUpdate.spec.ts +2 -2
  40. package/dist/actions/authentication.d.ts +0 -4
  41. package/dist/actions/authorization.d.ts +0 -3
  42. package/dist/actions/preferences.d.ts +0 -9
  43. package/dist/actions/preferences.spec.d.ts +0 -1
  44. package/dist/actions/userData.d.ts +0 -2
  45. package/dist/cache/engines/global.d.ts +0 -21
  46. package/dist/cache/engines/global.spec.d.ts +0 -1
  47. package/dist/cache/index.d.ts +0 -11
  48. package/dist/cache/index.spec.d.ts +0 -4
  49. package/dist/cache/types.d.ts +0 -11
  50. package/dist/clients/europa.d.ts +0 -17
  51. package/dist/clients/europa.spec.d.ts +0 -1
  52. package/dist/clients/jupiter.spec.d.ts +0 -1
  53. package/dist/clients/mercury.d.ts +0 -18
  54. package/dist/clients/mercury.spec.d.ts +0 -4
  55. package/dist/clients/nebula.d.ts +0 -2
  56. package/dist/clients/nebula.spec.d.ts +0 -1
  57. package/dist/clients/pluto.d.ts +0 -3
  58. package/dist/clients/pluto.spec.d.ts +0 -1
  59. package/dist/eventHandlers/activation.d.ts +0 -15
  60. package/dist/eventHandlers/authentication.d.ts +0 -17
  61. package/dist/eventHandlers/userAttributes.d.ts +0 -14
  62. package/dist/index-authentcation.spec.d.ts +0 -4
  63. package/dist/index-subscription.spec.d.ts +0 -4
  64. package/dist/index.js.LICENSE.txt +0 -14
  65. package/dist/lib/cookie.d.ts +0 -5
  66. package/dist/lib/rpc.d.ts +0 -6
  67. package/dist/store/index.d.ts +0 -13
  68. package/dist/store/index.spec.d.ts +0 -1
  69. package/dist/types.d.ts +0 -27
  70. package/dist/utils/customEventWrapper.d.ts +0 -17
  71. package/dist/utils/deepEquals.d.ts +0 -4
  72. package/dist/utils/getOrUpdate.d.ts +0 -6
  73. package/dist/utils/getOrUpdate.spec.d.ts +0 -1
  74. package/dist/utils/log.d.ts +0 -26
  75. package/dist/utils/queue.d.ts +0 -12
  76. package/dist/utils/url.d.ts +0 -3
  77. package/dist/utils/url.spec.d.ts +0 -1
@@ -0,0 +1,72 @@
1
+ import { Array, Literal, Record, String, Union } from 'runtypes';
2
+ const PublicationSchema = Record({
3
+ id: String,
4
+ domain: String,
5
+ });
6
+ export const CheckAccessForPaperSchema = Record({
7
+ status: Literal('success'),
8
+ access: Union(Literal('granted'), Literal('denied')),
9
+ publication: PublicationSchema,
10
+ access_features: Array(String),
11
+ });
12
+ const GetVstokenSchema = Record({
13
+ status: Literal('success'),
14
+ cookie: String,
15
+ access_features: Array(String),
16
+ });
17
+ const GetNonUserAccessSchema = Record({
18
+ status: Literal('success'),
19
+ vstoken_cookie: String,
20
+ uuid: String,
21
+ access_features: Array(String),
22
+ });
23
+ export const checkForAccess = (publicationDomain, accessFeatures) => fetch(`/api/jupiter/v1/check_access_for_paper/${publicationDomain}/?require=any&access_features=${accessFeatures.join(',')}`)
24
+ .then((response) => {
25
+ if (!response.ok) {
26
+ // TODO Handle this.
27
+ throw new Error(`Request not ok (${response.status}: ${response.statusText}).`);
28
+ }
29
+ return response.json();
30
+ })
31
+ .then((json) => {
32
+ try {
33
+ return CheckAccessForPaperSchema.check(json);
34
+ }
35
+ catch (error) {
36
+ console.error('Invalid schema', error);
37
+ throw error;
38
+ }
39
+ });
40
+ export const getVstoken = (publicationDomain) => fetch(`/api/jupiter/v1/get_vstoken/${publicationDomain}`, { method: "post" })
41
+ .then((response) => {
42
+ if (!response.ok) {
43
+ throw new Error(`Request not ok (${response.status}: ${response.statusText}).`);
44
+ }
45
+ return response.json();
46
+ })
47
+ .then((json) => {
48
+ try {
49
+ return GetVstokenSchema.check(json);
50
+ }
51
+ catch (error) {
52
+ console.error("Invalid schema", error);
53
+ throw error;
54
+ }
55
+ });
56
+ export const getNonUserAccess = (publicationDomain) => fetch(`/api/jupiter/v1/non_user_access/${publicationDomain}`, { method: "post" })
57
+ .then((response) => {
58
+ if (!response.ok) {
59
+ throw new Error(`Request not ok (${response.status}: ${response.statusText}).`);
60
+ }
61
+ return response.json();
62
+ })
63
+ .then((json) => {
64
+ try {
65
+ return GetNonUserAccessSchema.check(json);
66
+ }
67
+ catch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QUFDLENBQUM7S0FDRCxJQUFJLENBQUMsQ0FBQyxJQUFJLEVBQUUsRUFBRTtJQUNiLElBQUk7UUFDRixPQUFPLHNCQUFzQixDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsQ0FBQTtLQUMxQztJQUFDLE9BQU8sS0FBSyxFQUFFO1FBQ2QsT0FBTyxDQUFDLEtBQUssQ0FBQyxnQkFBZ0IsRUFBRSxLQUFLLENBQUMsQ0FBQTtRQUN0QyxNQUFNLEtBQUssQ0FBQztLQUNiO0FBQ0gsQ0FBQyxDQUFDLENBQUEifQ==
@@ -0,0 +1,12 @@
1
+ import { Optional, Record, Static, String } from 'runtypes';
2
+ export declare const SessionSchema: Record<{
3
+ created_at: String;
4
+ updated_at: String;
5
+ user_uuid: String;
6
+ user_name: String;
7
+ tracking_key: String;
8
+ user_agent: Optional<String>;
9
+ user_key: Optional<String>;
10
+ }, false>;
11
+ export declare type Session = Static<typeof SessionSchema>;
12
+ export declare const getCurrentSession: () => Promise<Session>;
@@ -0,0 +1,40 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { Optional, Record, String } from 'runtypes';
11
+ export const SessionSchema = Record({
12
+ created_at: String,
13
+ updated_at: String,
14
+ user_uuid: String,
15
+ user_name: String,
16
+ tracking_key: String,
17
+ user_agent: Optional(String),
18
+ // @deprecated Use tracking_key
19
+ user_key: Optional(String),
20
+ });
21
+ export const getCurrentSession = () => __awaiter(void 0, void 0, void 0, function* () {
22
+ return fetch(`/api/pluto/v1/sessions/current`)
23
+ .then((response) => {
24
+ if (!response.ok) {
25
+ // TODO Handle this.
26
+ throw new Error(`Request not ok (${response.status}: ${response.statusText}).`);
27
+ }
28
+ return response.json();
29
+ })
30
+ .then((json) => {
31
+ try {
32
+ return SessionSchema.check(json);
33
+ }
34
+ catch (error) {
35
+ console.error('Invalid schema', error);
36
+ throw error;
37
+ }
38
+ });
39
+ });
40
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicGx1dG8uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvc2VydmljZXMvcGx1dG8udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQUEsT0FBTyxFQUFFLFFBQVEsRUFBRSxNQUFNLEVBQVUsTUFBTSxFQUFFLE1BQU0sVUFBVSxDQUFDO0FBRTVELE1BQU0sQ0FBQyxNQUFNLGFBQWEsR0FBRyxNQUFNLENBQUM7SUFDbEMsVUFBVSxFQUFFLE1BQU07SUFDbEIsVUFBVSxFQUFFLE1BQU07SUFDbEIsU0FBUyxFQUFFLE1BQU07SUFDakIsU0FBUyxFQUFFLE1BQU07SUFDakIsWUFBWSxFQUFFLE1BQU07SUFDcEIsVUFBVSxFQUFFLFFBQVEsQ0FBQyxNQUFNLENBQUM7SUFFNUIsK0JBQStCO0lBQy9CLFFBQVEsRUFBRSxRQUFRLENBQUMsTUFBTSxDQUFDO0NBQzNCLENBQUMsQ0FBQztBQUdILE1BQU0sQ0FBQyxNQUFNLGlCQUFpQixHQUFHLEdBQTJCLEVBQUU7SUFDNUQsT0FBQSxLQUFLLENBQUMsZ0NBQWdDLENBQUM7U0FDcEMsSUFBSSxDQUFDLENBQUMsUUFBUSxFQUFFLEVBQUU7UUFDakIsSUFBSSxDQUFDLFFBQVEsQ0FBQyxFQUFFLEVBQUU7WUFDaEIsb0JBQW9CO1lBQ3BCLE1BQU0sSUFBSSxLQUFLLENBQ2IsbUJBQW1CLFFBQVEsQ0FBQyxNQUFNLEtBQUssUUFBUSxDQUFDLFVBQVUsSUFBSSxDQUMvRCxDQUFDO1NBQ0g7UUFDRCxPQUFPLFFBQVEsQ0FBQyxJQUFJLEVBQUUsQ0FBQztJQUN6QixDQUFDLENBQUM7U0FDRCxJQUFJLENBQUMsQ0FBQyxJQUFJLEVBQUUsRUFBRTtRQUNiLElBQUk7WUFDRixPQUFPLGFBQWEsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7U0FDbEM7UUFBQyxPQUFPLEtBQUssRUFBRTtZQUNkLE9BQU8sQ0FBQyxLQUFLLENBQUMsZ0JBQWdCLEVBQUUsS0FBSyxDQUFDLENBQUM7WUFDdkMsTUFBTSxLQUFLLENBQUM7U0FDYjtJQUNILENBQUMsQ0FBQyxDQUFBO0VBQUEsQ0FBQyJ9
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.7.3",
3
+ "version": "0.7.4",
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,9 +7,9 @@ import { logout } from './authentication';
7
7
  export const getAccess = (): Promise<Pick<UserAttributes, 'access'>> =>
8
8
  checkForAccess(getCurrentPublicationDomain(), ['newspaper']);
9
9
 
10
- export const activate = (accessFeature: string): Promise<boolean> => {
10
+ export const activate = (accessFeatures: string[]): Promise<boolean> => {
11
11
  try {
12
- return activateSubscription(accessFeature);
12
+ return activateSubscription(accessFeatures);
13
13
  } catch (error) {
14
14
  if (error instanceof UserDeactivatedError) {
15
15
  logout();
@@ -2,8 +2,6 @@ import fetch from 'jest-fetch-mock';
2
2
  import cache from '../cache';
3
3
  import { getPrivacyPreferences } from './preferences';
4
4
 
5
- fetch.enableMocks();
6
-
7
5
  beforeEach(() => {
8
6
  fetch.resetMocks();
9
7
  cache.clear();
@@ -14,7 +12,7 @@ const europaResponse = {
14
12
  privacy_preferences: {
15
13
  allow_research_usage: 'true',
16
14
  connect_with_surveys: true,
17
- personalizedAds: 'false',
15
+ personalized_ads: 'false',
18
16
  personalized_content: false,
19
17
  },
20
18
  },
@@ -6,7 +6,7 @@ import { Record, String } from 'runtypes';
6
6
  import * as MockDate from 'mockdate';
7
7
  import cache, { setCacheEngine } from '.';
8
8
  import log from '../utils/log';
9
- import resetAllMocks = jest.resetAllMocks;
9
+ import restoreAllMocks = jest.restoreAllMocks;
10
10
 
11
11
  const TestDataSchema = Record({
12
12
  test: String,
@@ -14,7 +14,7 @@ const TestDataSchema = Record({
14
14
 
15
15
  let mockEngine;
16
16
  beforeEach(() => {
17
- resetAllMocks();
17
+ restoreAllMocks();
18
18
  MockDate.reset();
19
19
  // @ts-ignore
20
20
  mockEngine = {
@@ -10,8 +10,6 @@ import {
10
10
  getAllNamespaces,
11
11
  } from './europa';
12
12
 
13
- fetch.enableMocks();
14
-
15
13
  beforeEach(() => {
16
14
  fetch.resetMocks();
17
15
  cache.clear();
@@ -10,6 +10,7 @@ import {
10
10
  GetNonUserAccess,
11
11
  getNonUserAccess,
12
12
  } from './jupiter';
13
+ import anything = jasmine.anything;
13
14
 
14
15
  beforeEach(async () => {
15
16
  fetch.resetMocks();
@@ -65,6 +66,31 @@ describe('jupiter service', () => {
65
66
  checkForAccess(publicationDomain, accessFeatures)
66
67
  ).rejects.toBeUndefined();
67
68
  });
69
+
70
+ it('should not cache when access denied', (done) => {
71
+ fetch.mockResponseOnce(
72
+ JSON.stringify({
73
+ status: 'success',
74
+ access: 'denied',
75
+ publication: {
76
+ domain: 'www.rb.no',
77
+ id: 95,
78
+ },
79
+ access_features: [],
80
+ })
81
+ );
82
+ const cacheSetSpy = spyOn(cache, 'set');
83
+ expect(checkForAccess(publicationDomain, accessFeatures))
84
+ .resolves.toEqual({ access: [] })
85
+ .then(() => {
86
+ expect(cacheSetSpy).toHaveBeenCalledWith(
87
+ 'checkForAccess',
88
+ anything(),
89
+ 0
90
+ );
91
+ })
92
+ .then(done);
93
+ });
68
94
  });
69
95
 
70
96
  describe('POST /get_vstoken', () => {
@@ -64,9 +64,10 @@ export const checkForAccess = (
64
64
  })
65
65
  .then((json) => {
66
66
  try {
67
+ const data = CheckAccessForPaperSchema.check(json);
67
68
  return {
68
- ttl: 1000 * 10, // 10 seconds
69
- data: CheckAccessForPaperSchema.check(json),
69
+ ttl: data.access === 'granted' ? 1000 * 10 : 0, // 10 seconds
70
+ data,
70
71
  };
71
72
  } catch (error) {
72
73
  log.error('Invalid schema', error);
@@ -8,8 +8,6 @@ import backendLog, {
8
8
  UserDeactivatedError,
9
9
  } from './mercury';
10
10
 
11
- fetch.enableMocks();
12
-
13
11
  beforeEach(() => {
14
12
  fetch.resetMocks();
15
13
  });
@@ -37,7 +35,7 @@ describe('activateSubscription()', () => {
37
35
  fetch.mockResponse(JSON.stringify({ status: 'user_deactivated' }), {
38
36
  status: 401,
39
37
  });
40
- return expect(activateSubscription('newspaper')).rejects.toThrow(
38
+ expect(activateSubscription(['newspaper'])).rejects.toThrow(
41
39
  UserDeactivatedError
42
40
  );
43
41
  });
@@ -46,25 +44,25 @@ describe('activateSubscription()', () => {
46
44
  fetch.mockResponse(JSON.stringify({ status: 'whatever' }), {
47
45
  status: 401,
48
46
  });
49
- return expect(activateSubscription('newspaper')).resolves.toBe(false);
47
+ expect(activateSubscription(['newspaper'])).resolves.toBe(false);
50
48
  });
51
49
 
52
50
  it('should return false if access is not "granted"', () => {
53
51
  fetch.mockResponse(JSON.stringify({ status: 'success', access: 'denied' }));
54
- return expect(activateSubscription('newspaper')).resolves.toBe(false);
52
+ expect(activateSubscription(['newspaper'])).resolves.toBe(false);
55
53
  });
56
54
 
57
55
  it('should return false if status is not "success"', () => {
58
56
  fetch.mockResponse(
59
57
  JSON.stringify({ status: 'unknown', access: 'granted' })
60
58
  );
61
- return expect(activateSubscription('newspaper')).resolves.toBe(false);
59
+ expect(activateSubscription(['newspaper'])).resolves.toBe(false);
62
60
  });
63
61
 
64
62
  it('should return true if status is "success" and access is "granted"', () => {
65
63
  fetch.mockResponse(
66
64
  JSON.stringify({ status: 'success', access: 'granted' })
67
65
  );
68
- return expect(activateSubscription('newspaper')).resolves.toBe(true);
66
+ expect(activateSubscription(['newspaper'])).resolves.toBe(true);
69
67
  });
70
68
  });
@@ -46,10 +46,12 @@ const log = {
46
46
  export class UserDeactivatedError extends Error {}
47
47
 
48
48
  export const activateSubscription = async (
49
- accessFeature: string
49
+ accessFeatures: string[]
50
50
  ): Promise<boolean> =>
51
51
  fetch(
52
- `/api/mercury/v2/access/activate?publication_wwwdomain=${getCurrentPublicationDomain()}&access_feature=${accessFeature}`,
52
+ `/api/mercury/v2/access/activate?publication_wwwdomain=${getCurrentPublicationDomain()}&access_features=${accessFeatures.join(
53
+ ','
54
+ )}`,
53
55
  {
54
56
  method: 'post',
55
57
  }
@@ -2,8 +2,6 @@ import fetch from 'jest-fetch-mock';
2
2
  import cache from '../cache';
3
3
  import { getCurrentSession, removeSession } from './pluto';
4
4
 
5
- fetch.enableMocks();
6
-
7
5
  beforeEach(async () => {
8
6
  fetch.resetMocks();
9
7
  await cache.clear();
@@ -9,7 +9,7 @@ export enum ActivationEvents {
9
9
  declare global {
10
10
  interface WindowEventMap {
11
11
  [ActivationEvents.REQUEST_ACTIVATION]: CustomEvent<{
12
- accessFeature: string;
12
+ accessFeatures: string[];
13
13
  }>;
14
14
  [ActivationEvents.ON_ACTIVATION_COMPLETE]: CustomEvent<{
15
15
  hasAccess: boolean;
@@ -19,7 +19,7 @@ declare global {
19
19
 
20
20
  export const listenForActivationRequests = () => {
21
21
  listenWithExclusivity(ActivationEvents.REQUEST_ACTIVATION, (evt) => {
22
- activate(evt.detail.accessFeature).then((result) => {
22
+ activate(evt.detail.accessFeatures).then((result) => {
23
23
  dispatch(
24
24
  new CustomEvent(ActivationEvents.ON_ACTIVATION_COMPLETE, {
25
25
  detail: { hasAccess: result },
@@ -6,9 +6,10 @@ import { goToLoginPage, logout } from './index';
6
6
  import { setRootElement } from './utils/customEventWrapper';
7
7
  import * as authentication from './actions/authentication';
8
8
  import { listenForAuthenticationRequests } from './eventHandlers/authentication';
9
+ import restoreAllMocks = jest.restoreAllMocks;
9
10
 
10
11
  beforeEach(() => {
11
- jest.resetAllMocks();
12
+ restoreAllMocks();
12
13
 
13
14
  // We cannot use window as our event root during testing
14
15
  // since tests are executed in parallel.
@@ -2,14 +2,15 @@
2
2
  * @jest-environment jsdom
3
3
  */
4
4
 
5
- import { subscribeToUserAttributes } from './index';
5
+ import { User } from './index';
6
6
  import * as userData from './actions/userData';
7
7
  import { setRootElement } from './utils/customEventWrapper';
8
8
  import { listenForUserAttributeRequests } from './eventHandlers/userAttributes';
9
9
  import store from './store';
10
+ import restoreAllMocks = jest.restoreAllMocks;
10
11
 
11
12
  beforeEach(() => {
12
- jest.resetAllMocks();
13
+ restoreAllMocks();
13
14
 
14
15
  // We cannot use window as our event root during testing
15
16
  // since tests are executed in parallel.
@@ -30,7 +31,7 @@ describe('Public endpoint - userdata', () => {
30
31
  });
31
32
 
32
33
  const onUserUpdate = jest.fn();
33
- subscribeToUserAttributes(['name'], onUserUpdate);
34
+ new User().withAttributes(['name']).subscribe(onUserUpdate);
34
35
 
35
36
  expect(onUserUpdate).toHaveBeenCalledWith({
36
37
  name: 'Donald Duck',
@@ -42,10 +43,13 @@ describe('Public endpoint - userdata', () => {
42
43
  store.set('userAttributes', { name: 'Donald Duck' });
43
44
  });
44
45
 
46
+ const userUpdates = new User();
47
+
45
48
  const onUserUpdate1 = jest.fn();
46
- subscribeToUserAttributes(['name'], onUserUpdate1);
49
+ userUpdates.withAttributes(['name']).subscribe(onUserUpdate1);
50
+
47
51
  const onUserUpdate2 = jest.fn();
48
- subscribeToUserAttributes(['name'], onUserUpdate2);
52
+ userUpdates.withAttributes(['name']).subscribe(onUserUpdate2);
49
53
 
50
54
  expect(onUserUpdate1).toHaveBeenCalledTimes(1);
51
55
  expect(onUserUpdate1).toHaveBeenCalledWith({
@@ -68,11 +72,13 @@ describe('Public endpoint - userdata', () => {
68
72
  store.set('userAttributes', { name: 'Donald Duck' })
69
73
  );
70
74
 
75
+ const userUpdates = new User();
76
+
71
77
  const firstOnUserUpdate = jest.fn();
72
- subscribeToUserAttributes(['name'], firstOnUserUpdate);
78
+ userUpdates.withAttributes(['name']).subscribe(firstOnUserUpdate);
73
79
 
74
80
  const secondOnUserUpdate = jest.fn();
75
- subscribeToUserAttributes(['name'], secondOnUserUpdate);
81
+ userUpdates.withAttributes(['name']).subscribe(secondOnUserUpdate);
76
82
 
77
83
  expect(firstOnUserUpdate).toHaveBeenCalledTimes(2);
78
84
  expect(firstOnUserUpdate).nthCalledWith(1, {});
@@ -95,7 +101,7 @@ describe('Public endpoint - userdata', () => {
95
101
  });
96
102
 
97
103
  const onUserUpdate = jest.fn();
98
- subscribeToUserAttributes(['name'], onUserUpdate);
104
+ new User().withAttributes(['name']).subscribe(onUserUpdate);
99
105
 
100
106
  expect(onUserUpdate).toHaveBeenCalledWith({
101
107
  name: 'Donald Duck',
@@ -111,7 +117,7 @@ describe('Public endpoint - userdata', () => {
111
117
  });
112
118
 
113
119
  const onUserUpdate = jest.fn();
114
- subscribeToUserAttributes(['name', 'email'], onUserUpdate);
120
+ new User().withAttributes(['name', 'email']).subscribe(onUserUpdate);
115
121
 
116
122
  expect(onUserUpdate).toHaveBeenCalledWith({
117
123
  name: 'Donald Duck',
@@ -121,7 +127,7 @@ describe('Public endpoint - userdata', () => {
121
127
 
122
128
  it('should require at least one attribute', () => {
123
129
  const onUserUpdate = jest.fn();
124
- expect(() => subscribeToUserAttributes([], onUserUpdate)).toThrowError(
130
+ expect(() => new User().subscribe(onUserUpdate)).toThrowError(
125
131
  new Error('You must subscribe to at least one attribute')
126
132
  );
127
133
  });
@@ -135,10 +141,10 @@ describe('Public endpoint - userdata', () => {
135
141
  });
136
142
 
137
143
  const firstOnUserUpdate = jest.fn();
138
- subscribeToUserAttributes(['name', 'email'], firstOnUserUpdate);
144
+ new User().withAttributes(['name', 'email']).subscribe(firstOnUserUpdate);
139
145
 
140
146
  const secondOnUserUpdate = jest.fn();
141
- subscribeToUserAttributes(['email'], secondOnUserUpdate);
147
+ new User().withAttributes(['email']).subscribe(secondOnUserUpdate);
142
148
 
143
149
  expect(firstOnUserUpdate).toHaveBeenCalledTimes(1);
144
150
  expect(firstOnUserUpdate).nthCalledWith(1, {
@@ -162,7 +168,8 @@ describe('Public endpoint - userdata', () => {
162
168
 
163
169
  const onUserUpdate = jest.fn();
164
170
  const onStateUpdate = jest.fn();
165
- subscribeToUserAttributes(['name'], onUserUpdate, onStateUpdate);
171
+
172
+ new User().withAttributes(['name']).subscribe(onUserUpdate, onStateUpdate);
166
173
 
167
174
  expect(onUserUpdate).toHaveBeenCalledWith({ name: 'Donald Duck' });
168
175
  expect(onStateUpdate).toHaveBeenCalledWith({ isLoggedIn: true });
package/src/index.ts CHANGED
@@ -10,46 +10,70 @@ import { deepEquals } from './utils/deepEquals';
10
10
  * Enables you to subscribe to the user attributes you care about and
11
11
  * get notified when something changes
12
12
  */
13
- export const subscribeToUserAttributes = <
14
- T extends Array<keyof UserAttributes>
15
- >(
16
- attributes: T,
17
- onUserUpdated: (attributes: Pick<UserAttributes, T[number]>) => void,
18
- onStateUpdated?: (attributes: State) => void
19
- ) => {
20
- if (!attributes || attributes.length === 0) {
21
- throw new Error('You must subscribe to at least one attribute');
13
+
14
+ export class User {
15
+ private attributes: Array<keyof UserAttributes> = [];
16
+
17
+ private namespaces: Array<string> = [];
18
+
19
+ private extraData?: Array<string> = [];
20
+
21
+ withAttributes(attributes: Array<keyof UserAttributes>): this {
22
+ this.attributes = attributes;
23
+ return this;
22
24
  }
23
- let previousUserAttributes: Pick<UserAttributes, T[number]>;
24
- listenForAllEvents(AmediaUserEvents.ON_ATTRIBUTES_UPDATED, (evt) => {
25
- const userAttributes = evt.detail;
26
25
 
27
- // Reduce responseAttributes to match requested attributes
28
- const responseAttributes = attributes.reduce((map, attribute) => {
29
- if (userAttributes[attribute] !== undefined) {
30
- // eslint-disable-next-line no-param-reassign
31
- map[attribute] = userAttributes[attribute];
32
- }
33
- return map;
34
- }, {} as Pick<UserAttributes, T[number]>);
26
+ withStorage(namespaces: Array<string>): this {
27
+ this.namespaces = namespaces;
28
+ return this;
29
+ }
30
+
31
+ withExtraData(extraData?: Array<string>): this {
32
+ this.extraData = extraData;
33
+ return this;
34
+ }
35
35
 
36
- if (deepEquals(previousUserAttributes, responseAttributes)) {
37
- return;
36
+ subscribe(
37
+ onUserUpdated: (attributes: UserAttributes) => void,
38
+ onStateUpdated?: (state: State) => void
39
+ ): void {
40
+ if (!this.attributes || this.attributes.length === 0) {
41
+ throw new Error('You must subscribe to at least one attribute');
38
42
  }
39
- onUserUpdated(responseAttributes);
40
- previousUserAttributes = responseAttributes;
41
- });
42
- if (onStateUpdated) {
43
- listenForAllEvents(AmediaUserEvents.ON_STATE_UPDATED, (evt) => {
44
- onStateUpdated(evt.detail);
43
+ let previousUserAttributes: UserAttributes;
44
+ listenForAllEvents(AmediaUserEvents.ON_ATTRIBUTES_UPDATED, (evt) => {
45
+ const userAttributes = evt.detail;
46
+
47
+ // Reduce responseAttributes to match requested attributes
48
+ const responseAttributes = this.attributes.reduce((map, attribute) => {
49
+ if (userAttributes[attribute] !== undefined) {
50
+ // @ts-ignore
51
+ // eslint-disable-next-line no-param-reassign
52
+ map[attribute] = userAttributes[attribute];
53
+ }
54
+ return map;
55
+ }, {} as UserAttributes);
56
+
57
+ if (deepEquals(previousUserAttributes, responseAttributes)) {
58
+ return;
59
+ }
60
+
61
+ onUserUpdated(responseAttributes);
62
+ previousUserAttributes = responseAttributes;
45
63
  });
64
+
65
+ if (onStateUpdated) {
66
+ listenForAllEvents(AmediaUserEvents.ON_STATE_UPDATED, (evt) => {
67
+ onStateUpdated(evt.detail);
68
+ });
69
+ }
70
+ dispatch(
71
+ new CustomEvent(AmediaUserEvents.REQUEST_USER_ATTRIBUTES, {
72
+ detail: this.attributes,
73
+ })
74
+ );
46
75
  }
47
- dispatch(
48
- new CustomEvent(AmediaUserEvents.REQUEST_USER_ATTRIBUTES, {
49
- detail: attributes,
50
- })
51
- );
52
- };
76
+ }
53
77
 
54
78
  /**
55
79
  * This will, if necessary, trigger a redirect to www.aid.no and return
@@ -3,12 +3,12 @@ import cache from '../cache';
3
3
  import getOrUpdate from './getOrUpdate';
4
4
  import queue from './queue';
5
5
  import spyOn = jest.spyOn;
6
- import resetAllMocks = jest.resetAllMocks;
6
+ import restoreAllMocks = jest.restoreAllMocks;
7
7
 
8
8
  const schema = Partial({ field: String, extraField: String });
9
9
 
10
10
  beforeEach(async () => {
11
- resetAllMocks();
11
+ restoreAllMocks();
12
12
  await cache.clear();
13
13
  });
14
14
  describe('getOrUpdate', () => {
@@ -1,4 +0,0 @@
1
- import { UserAttributes } from '../types';
2
- export declare const login: (requestedUrl: string) => void;
3
- export declare const logout: () => Promise<void>;
4
- export declare const getSession: () => Promise<UserAttributes>;
@@ -1,3 +0,0 @@
1
- import { UserAttributes } from '../types';
2
- export declare const getAccess: () => Promise<Pick<UserAttributes, 'access'>>;
3
- export declare const activate: (accessFeature: string) => Promise<boolean>;
@@ -1,9 +0,0 @@
1
- import { Record, Boolean } from 'runtypes';
2
- import { UserAttributes } from '../types';
3
- export declare const PrivacyPreferencesSchema: Record<{
4
- allowResearchUsage: Boolean;
5
- connectWithSurveys: Boolean;
6
- personalizedAds: Boolean;
7
- personalizedContent: Boolean;
8
- }, false>;
9
- export declare const getPrivacyPreferences: () => Promise<Pick<UserAttributes, 'privacyPreferences'>>;
@@ -1 +0,0 @@
1
- export {};
@@ -1,2 +0,0 @@
1
- import { UserAttributes } from '../types';
2
- export declare const requestAttributes: (attributes: Array<keyof UserAttributes>) => void;
@@ -1,21 +0,0 @@
1
- import { CacheEntry, Engine } from '../types';
2
- declare global {
3
- interface Window {
4
- amediaUserCache?: {
5
- [index: string]: CacheEntry;
6
- };
7
- }
8
- namespace NodeJS {
9
- interface Global {
10
- amediaUserCache?: {
11
- [index: string]: CacheEntry;
12
- };
13
- }
14
- }
15
- }
16
- export declare const get: (key: string) => Promise<CacheEntry>;
17
- export declare const set: (key: string, data: unknown, expires: number) => Promise<void>;
18
- export declare const remove: (key: string) => Promise<void>;
19
- export declare const clear: () => Promise<void>;
20
- declare const _default: Engine;
21
- export default _default;
@@ -1 +0,0 @@
1
- export {};
@@ -1,11 +0,0 @@
1
- import { Static } from 'runtypes';
2
- import { RuntypeBase } from 'runtypes/lib/runtype';
3
- import { Engine } from './types';
4
- export declare const setCacheEngine: (engine: Engine) => void;
5
- declare const _default: {
6
- get: <T extends RuntypeBase<unknown>>(key: string, validator: T) => Promise<void | Static<T>>;
7
- set: (key: string, value: unknown, expires: number) => Promise<void>;
8
- remove: (key: string) => Promise<void>;
9
- clear: () => Promise<void>;
10
- };
11
- export default _default;