@amedia/user 0.3.2 → 0.4.1

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 (59) hide show
  1. package/.eslintignore +2 -0
  2. package/.eslintrc +8 -3
  3. package/dist/actions/authentication.d.ts +1 -1
  4. package/dist/actions/authorization.d.ts +6 -2
  5. package/dist/cache/engines/global.d.ts +15 -0
  6. package/dist/cache/engines/global.spec.d.ts +1 -0
  7. package/dist/cache/engines/indexeddb.d.ts +1 -0
  8. package/dist/cache/index.d.ts +1 -0
  9. package/dist/cache/index.spec.d.ts +4 -0
  10. package/dist/cache/types.d.ts +1 -0
  11. package/dist/eventHandlers/authentication.d.ts +5 -3
  12. package/dist/index-authentcation.spec.d.ts +4 -0
  13. package/dist/index-userdata.spec.d.ts +4 -0
  14. package/dist/index.d.ts +3 -1
  15. package/dist/index.js +1 -1
  16. package/dist/lib/cookie.d.ts +5 -0
  17. package/dist/lib/rpc.d.ts +1 -0
  18. package/dist/services/jupiter.spec.d.ts +1 -0
  19. package/dist/services/mercury.spec.d.ts +4 -0
  20. package/dist/services/pluto.d.ts +2 -2
  21. package/dist/services/pluto.spec.d.ts +1 -0
  22. package/dist/utils/log.d.ts +7 -0
  23. package/dist/utils/queue.d.ts +9 -2
  24. package/package.json +5 -4
  25. package/src/actions/authentication.ts +28 -5
  26. package/src/actions/authorization.ts +42 -38
  27. package/src/{lib/dataOrganizer.ts → actions/userData.ts} +5 -2
  28. package/src/cache/engines/global.spec.ts +62 -0
  29. package/src/cache/engines/global.ts +25 -7
  30. package/src/cache/engines/indexeddb.ts +3 -1
  31. package/src/cache/index.spec.ts +33 -1
  32. package/src/cache/index.ts +8 -1
  33. package/src/cache/types.ts +1 -0
  34. package/src/eventHandlers/authentication.ts +10 -5
  35. package/src/eventHandlers/userAttributes.ts +1 -1
  36. package/src/index-authentcation.spec.ts +44 -0
  37. package/src/{index.spec.ts → index-userdata.spec.ts} +8 -15
  38. package/src/index.ts +9 -6
  39. package/src/lib/cookie.ts +109 -0
  40. package/src/lib/rpc.ts +15 -0
  41. package/src/services/jupiter.spec.ts +5 -3
  42. package/src/services/jupiter.ts +5 -3
  43. package/src/services/pluto.ts +8 -6
  44. package/src/utils/log.ts +29 -2
  45. package/src/utils/queue.ts +19 -4
  46. package/tsconfig.json +2 -0
  47. package/webpack.config.js +1 -1
  48. package/.babelrc +0 -3
  49. package/dist/lib/authentication.d.ts +0 -20
  50. package/dist/lib/authorization.d.ts +0 -15
  51. package/dist/lib/cache/db.d.ts +0 -6
  52. package/dist/lib/cache/global.d.ts +0 -9
  53. package/dist/lib/cache/types.d.ts +0 -5
  54. package/dist/lib/eventHandler.d.ts +0 -3
  55. package/dist/lib/queue.d.ts +0 -5
  56. package/dist/lib/types.d.ts +0 -7
  57. package/dist/lib/userAttributes.d.ts +0 -12
  58. package/dist/services/cache.d.ts +0 -9
  59. /package/dist/{lib/dataOrganizer.d.ts → actions/userData.d.ts} +0 -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
+ });
@@ -1,12 +1,25 @@
1
1
  import { CacheEntry, Engine } from '../types';
2
2
 
3
- // eslint-disable-next-line no-multi-assign
4
- const cache = ((typeof window !== 'undefined' ? window : global)[
5
- 'amedia-user-cache'
6
- ] = {});
3
+ declare global {
4
+ interface Window {
5
+ amediaUserCache?: { [index: string]: CacheEntry };
6
+ }
7
+
8
+ namespace NodeJS {
9
+ interface Global {
10
+ amediaUserCache?: { [index: string]: CacheEntry };
11
+ }
12
+ }
13
+ }
14
+
15
+ const getStorage = () => {
16
+ const rootObject = typeof window !== 'undefined' ? window : global;
17
+ // eslint-disable-next-line no-return-assign
18
+ return rootObject.amediaUserCache || (rootObject.amediaUserCache = {});
19
+ };
7
20
 
8
21
  export const get = (key: string): Promise<CacheEntry> => {
9
- const data = cache[key];
22
+ const data = getStorage()[key];
10
23
  return Promise.resolve(data);
11
24
  };
12
25
 
@@ -15,12 +28,17 @@ export const set = (
15
28
  data: unknown,
16
29
  expires: number
17
30
  ): Promise<void> => {
18
- cache[key] = { key, data, expires };
31
+ getStorage()[key] = { key, data, expires };
19
32
  return Promise.resolve();
20
33
  };
21
34
 
22
35
  export const remove = (key: string): Promise<void> => {
23
- delete cache[key];
36
+ delete getStorage()[key];
37
+ return Promise.resolve();
38
+ };
39
+
40
+ export const clear = (): Promise<void> => {
41
+ (typeof window !== 'undefined' ? window : global).amediaUserCache = {};
24
42
  return Promise.resolve();
25
43
  };
26
44
 
@@ -18,4 +18,6 @@ export const set = (
18
18
  });
19
19
  export const remove = (key: string): Promise<void> => cache.delete(key);
20
20
 
21
- export default { get, set, remove } as Engine;
21
+ export const clear = (): Promise<void> => cache.clear();
22
+
23
+ export default { get, set, remove, clear } as Engine;
@@ -15,7 +15,12 @@ let mockEngine;
15
15
  beforeEach(() => {
16
16
  resetAllMocks();
17
17
  // @ts-ignore
18
- mockEngine = { get: jest.fn(), set: jest.fn(), remove: jest.fn() };
18
+ mockEngine = {
19
+ get: jest.fn(),
20
+ set: jest.fn(),
21
+ remove: jest.fn(),
22
+ clear: jest.fn(),
23
+ };
19
24
  // @ts-ignore
20
25
  setCacheEngine(mockEngine);
21
26
  log.error = jest.fn();
@@ -78,4 +83,31 @@ describe('Cache', () => {
78
83
  expect(mockEngine.remove).toHaveBeenCalledWith('foo');
79
84
  });
80
85
  });
86
+
87
+ describe('set', () => {
88
+ it('should set', () => {
89
+ cache.set('test-key', { test: 'data' }, 1234567890);
90
+ expect(mockEngine.set).toHaveBeenCalledWith(
91
+ 'test-key',
92
+ { test: 'data' },
93
+ 1234567890
94
+ );
95
+ });
96
+ });
97
+
98
+ describe('remove', () => {
99
+ it('should remove', () => {
100
+ expect(mockEngine.remove).not.toHaveBeenCalled();
101
+ cache.remove('some-key');
102
+ expect(mockEngine.remove).toHaveBeenCalledWith('some-key');
103
+ });
104
+ });
105
+
106
+ describe('clear', () => {
107
+ it('should clear', () => {
108
+ expect(mockEngine.clear).not.toHaveBeenCalled();
109
+ cache.clear();
110
+ expect(mockEngine.clear).toHaveBeenCalled();
111
+ });
112
+ });
81
113
  });
@@ -45,4 +45,11 @@ const get = async <T extends Record<any, any>>(
45
45
  }
46
46
  };
47
47
 
48
- export default { get, set, remove };
48
+ const clear = () => getCacheEngine().clear();
49
+
50
+ export default {
51
+ get,
52
+ set,
53
+ remove,
54
+ clear,
55
+ };
@@ -8,4 +8,5 @@ export type Engine = {
8
8
  get: (key: string) => Promise<CacheEntry | null>;
9
9
  set: (key: string, data: unknown, expires: number) => Promise<void>;
10
10
  remove: (key: string) => Promise<void>;
11
+ clear: () => Promise<void>;
11
12
  };
@@ -1,29 +1,34 @@
1
- import { listenWithExclusivity } from '../utils/customEventWrapper';
1
+ import { dispatch, listenWithExclusivity } from '../utils/customEventWrapper';
2
2
  import { login, logout } from '../actions/authentication';
3
3
 
4
4
  export enum AuthenticationEvents {
5
5
  REQUEST_LOGIN = 'amedia-user.authentication.request-login',
6
6
  REQUEST_LOGOUT = 'amedia-user.authentication.request-logout',
7
+
8
+ ON_LOGGED_OUT = 'amedia-user.authentication.on-logged-out',
7
9
  }
8
10
 
9
11
  declare global {
10
12
  interface WindowEventMap {
11
13
  [AuthenticationEvents.REQUEST_LOGIN]: CustomEvent<{
12
- requestedUrl?: string;
14
+ requestedUrl: string;
13
15
  }>;
14
16
  [AuthenticationEvents.REQUEST_LOGOUT]: CustomEvent<{
15
- requestedUrl?: string;
17
+ onLoggedOut: () => void;
16
18
  }>;
19
+ [AuthenticationEvents.ON_LOGGED_OUT]: CustomEvent;
17
20
  }
18
21
  }
19
22
 
20
23
  export const listenForAuthenticationRequests = () => {
21
24
  listenWithExclusivity(AuthenticationEvents.REQUEST_LOGIN, (evt) => {
22
- login(evt.detail.requestedUrl || window.location.href);
25
+ login(evt.detail.requestedUrl);
23
26
  });
24
27
 
25
28
  listenWithExclusivity(AuthenticationEvents.REQUEST_LOGOUT, () => {
26
- logout();
29
+ logout().finally(() => {
30
+ dispatch(new CustomEvent(AuthenticationEvents.ON_LOGGED_OUT));
31
+ });
27
32
  });
28
33
  };
29
34
  listenForAuthenticationRequests();
@@ -1,4 +1,4 @@
1
- import { fetchDataBasedOnAttributes } from '../lib/dataOrganizer';
1
+ import { fetchDataBasedOnAttributes } from '../actions/userData';
2
2
  import { dispatch, listenWithExclusivity } from '../utils/customEventWrapper';
3
3
  import { UserAttributes } from '../types';
4
4
 
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+
5
+ import { login, logout } from './index';
6
+ import { setRootElement } from './utils/customEventWrapper';
7
+ import * as authentication from './actions/authentication';
8
+ import { listenForAuthenticationRequests } from './eventHandlers/authentication';
9
+
10
+ beforeEach(() => {
11
+ jest.resetAllMocks();
12
+
13
+ // We cannot use window as our event root during testing
14
+ // since tests are executed in parallel.
15
+ setRootElement(new Document());
16
+
17
+ // Also, since we keep creating new root elements, we also
18
+ // need to attach to these new roots.
19
+ listenForAuthenticationRequests();
20
+ });
21
+
22
+ describe('Public endpoint - authentication', () => {
23
+ it('should call callback on logout complete', (done) => {
24
+ jest
25
+ .spyOn(authentication, 'logout')
26
+ .mockImplementation(() => Promise.resolve());
27
+
28
+ const onLoggedOut = jest.fn();
29
+ logout(onLoggedOut);
30
+ setTimeout(() => {
31
+ expect(authentication.logout).toHaveBeenCalledTimes(1);
32
+ expect(onLoggedOut).toHaveBeenCalled();
33
+ done();
34
+ });
35
+ });
36
+
37
+ it('should login', () => {
38
+ jest.spyOn(authentication, 'login').mockImplementation();
39
+ login('https://www.avisnavn.no');
40
+ expect(authentication.login).toHaveBeenCalledWith(
41
+ 'https://www.avisnavn.no'
42
+ );
43
+ });
44
+ });
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import { subscribeToUserUpdates } from './index';
6
- import * as dataOrganizer from './lib/dataOrganizer';
6
+ import * as userData from './actions/userData';
7
7
  import { setRootElement } from './utils/customEventWrapper';
8
8
  import { listenForUserAttributeRequests } from './eventHandlers/userAttributes';
9
9
 
@@ -19,14 +19,13 @@ beforeEach(() => {
19
19
  listenForUserAttributeRequests();
20
20
  });
21
21
 
22
- describe('Public endpoint', () => {
22
+ describe('Public endpoint - userdata', () => {
23
23
  it('should alert about user data', () => {
24
24
  jest
25
- .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
25
+ .spyOn(userData, 'fetchDataBasedOnAttributes')
26
26
  .mockImplementation((_, callback: Function) => {
27
27
  callback({
28
28
  name: 'Donald Duck',
29
- isLoggedIn: true,
30
29
  });
31
30
  });
32
31
 
@@ -41,17 +40,15 @@ describe('Public endpoint', () => {
41
40
 
42
41
  it('should alert when others also ask about data', () => {
43
42
  jest
44
- .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
43
+ .spyOn(userData, 'fetchDataBasedOnAttributes')
45
44
  .mockImplementationOnce((_, callback: Function) => {
46
45
  callback({
47
46
  name: undefined,
48
- isLoggedIn: false,
49
47
  });
50
48
  })
51
49
  .mockImplementationOnce((_, callback: Function) => {
52
50
  callback({
53
51
  name: 'Donald Duck',
54
- isLoggedIn: true,
55
52
  });
56
53
  });
57
54
 
@@ -80,12 +77,11 @@ describe('Public endpoint', () => {
80
77
 
81
78
  it('should not return more data that requested (except for login status)', () => {
82
79
  jest
83
- .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
80
+ .spyOn(userData, 'fetchDataBasedOnAttributes')
84
81
  .mockImplementationOnce((_, callback: Function) => {
85
82
  callback({
86
83
  name: 'Donald Duck',
87
84
  email: 'donald.duck@andeby.no',
88
- isLoggedIn: true,
89
85
  });
90
86
  });
91
87
 
@@ -100,13 +96,12 @@ describe('Public endpoint', () => {
100
96
 
101
97
  it('should support returning multiple requested attributes', () => {
102
98
  jest
103
- .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
99
+ .spyOn(userData, 'fetchDataBasedOnAttributes')
104
100
 
105
101
  .mockImplementationOnce((_, callback: Function) => {
106
102
  callback({
107
103
  name: 'Donald Duck',
108
104
  email: 'donald.duck@andeby.no',
109
- isLoggedIn: true,
110
105
  });
111
106
  });
112
107
 
@@ -122,12 +117,11 @@ describe('Public endpoint', () => {
122
117
 
123
118
  it('should support no attributes, returning only logged in state', () => {
124
119
  jest
125
- .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
120
+ .spyOn(userData, 'fetchDataBasedOnAttributes')
126
121
  .mockImplementationOnce((_, callback: Function) => {
127
122
  callback({
128
123
  name: 'Donald Duck',
129
124
  email: 'donald.duck@andeby.no',
130
- isLoggedIn: true,
131
125
  });
132
126
  });
133
127
 
@@ -141,12 +135,11 @@ describe('Public endpoint', () => {
141
135
 
142
136
  it('should support requesting different attributes', () => {
143
137
  jest
144
- .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
138
+ .spyOn(userData, 'fetchDataBasedOnAttributes')
145
139
  .mockImplementation((_, callback: Function) => {
146
140
  callback({
147
141
  name: 'Donald Duck',
148
142
  email: 'donald.duck@andeby.no',
149
- isLoggedIn: true,
150
143
  });
151
144
  });
152
145
 
package/src/index.ts CHANGED
@@ -63,17 +63,20 @@ export const subscribeToUserUpdates = <T extends Array<keyof UserAttributes>>(
63
63
  * to the requestedUrl if supplied or the current url before redirecting away if not.
64
64
  * @param requestedUrl
65
65
  */
66
- export const requestLogin = (requestedUrl?: string) =>
66
+ export const login = (requestedUrl?: string) =>
67
67
  dispatch(
68
68
  new CustomEvent(AuthenticationEvents.REQUEST_LOGIN, {
69
- detail: { requestedUrl },
69
+ detail: { requestedUrl: requestedUrl || window.location.href },
70
70
  })
71
71
  );
72
72
 
73
+ export const logout = (onLoggedOut: () => void) => {
74
+ listenForAllEvents(AuthenticationEvents.ON_LOGGED_OUT, onLoggedOut);
75
+ dispatch(new CustomEvent(AuthenticationEvents.REQUEST_LOGOUT));
76
+ };
77
+
73
78
  export const activate = (): Promise<unknown> =>
74
- new Promise((resolve, reject) => {
75
- listenForAllEvents(ActivationEvents.ON_ACTIVATION_COMPLETE, (result) => {
76
- resolve(result);
77
- });
79
+ new Promise((resolve) => {
80
+ listenForAllEvents(ActivationEvents.ON_ACTIVATION_COMPLETE, resolve);
78
81
  dispatch(new CustomEvent(ActivationEvents.REQUEST_ACTIVATION));
79
82
  });
@@ -0,0 +1,109 @@
1
+ const getCookieValue = (
2
+ nameEQ: string,
3
+ c: string
4
+ ): undefined | null | string | { [index: string]: unknown } => {
5
+ const value = c.substring(nameEQ.length, c.length);
6
+
7
+ if (value.substring(0, 1) === '{') {
8
+ return JSON.parse(value);
9
+ }
10
+
11
+ if (value.substring(0, 3) === '%7B') {
12
+ return JSON.parse(decodeURIComponent(value));
13
+ }
14
+
15
+ if (value === 'undefined') {
16
+ return undefined;
17
+ }
18
+
19
+ if (value === '' || value === 'null') {
20
+ return null;
21
+ }
22
+
23
+ return value;
24
+ };
25
+
26
+ export const getCookie = (name: string) => {
27
+ const nameEQ = `${name}=`;
28
+ const ca = document.cookie.split(';');
29
+
30
+ for (let i = ca.length - 1; i >= 0; i -= 1) {
31
+ const c = ca[i].trim();
32
+ if (c.indexOf(nameEQ) === 0) {
33
+ return getCookieValue(nameEQ, c);
34
+ }
35
+ }
36
+ return null;
37
+ };
38
+
39
+ const setValidTime = (date: Date, validTimeDateOrDays?: Date | number) => {
40
+ if (!validTimeDateOrDays) {
41
+ return '';
42
+ }
43
+
44
+ if (validTimeDateOrDays instanceof Date) {
45
+ return `; expires=${validTimeDateOrDays.toUTCString()}`;
46
+ }
47
+ /* Assume validTime is given in days */
48
+ date.setTime(date.getTime() + validTimeDateOrDays * 24 * 60 * 60 * 1000);
49
+ return `; expires=${date.toUTCString()}`;
50
+ };
51
+
52
+ const setValue = (value: unknown): string => {
53
+ if (!value || value === '') {
54
+ return '';
55
+ }
56
+ if (value instanceof Object) {
57
+ return encodeURIComponent(JSON.stringify(value));
58
+ }
59
+
60
+ if (typeof value === 'number') {
61
+ return value.toString(10);
62
+ }
63
+ return <string>value;
64
+ };
65
+
66
+ export function setCookie(
67
+ name: string,
68
+ value?: unknown,
69
+ validTimeInDateOrDays: Date | number = Date.now(),
70
+ path = '/',
71
+ secure: boolean = false
72
+ ) {
73
+ const date = new Date();
74
+
75
+ let cookiestring = `${name}=`;
76
+
77
+ /* If value is empty or not set, handle as a cookie delete */
78
+ if (!value || value === '') {
79
+ // eslint-disable-next-line no-param-reassign
80
+ validTimeInDateOrDays = -1;
81
+ }
82
+
83
+ cookiestring += setValue(value);
84
+ cookiestring += setValidTime(date, validTimeInDateOrDays);
85
+ cookiestring += `; path=${path}`;
86
+
87
+ if (secure) {
88
+ cookiestring += '; secure';
89
+ }
90
+
91
+ document.cookie = cookiestring;
92
+
93
+ if (
94
+ validTimeInDateOrDays &&
95
+ validTimeInDateOrDays !== -1 &&
96
+ getCookie(name) === null
97
+ ) {
98
+ /**
99
+ * IE has a mode where user can choose to only accept session cookies, if we were unable to set it with
100
+ * expires, we need to try setting it without expires to trigger setting it as session cookie for these users.
101
+ */
102
+ document.cookie = cookiestring.replace(/; expires=[^;]*/, '');
103
+ }
104
+ return cookiestring;
105
+ }
106
+
107
+ export function removeCookie(name): void {
108
+ setCookie(name);
109
+ }
package/src/lib/rpc.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { RPCclient } from '@amedia/frontend-rpc';
2
+
3
+ let rpcSessionClient;
4
+ export const getRPCClient = () => {
5
+ if (rpcSessionClient) {
6
+ return rpcSessionClient;
7
+ }
8
+ rpcSessionClient = new RPCclient({
9
+ version: '1.0.0',
10
+ component: `userdata-session`,
11
+ });
12
+
13
+ rpcSessionClient.addMethod('userAuthenticated');
14
+ return rpcSessionClient;
15
+ };
@@ -1,4 +1,6 @@
1
+ /* eslint-disable no-console */
1
2
  import fetch from 'jest-fetch-mock';
3
+ import log from '../utils/log';
2
4
  import {
3
5
  checkForAccess,
4
6
  getVstoken,
@@ -52,7 +54,7 @@ describe('/check_access_for_paper', () => {
52
54
 
53
55
  it('should fail on runtime validation', async () => {
54
56
  fetch.mockResponseOnce(JSON.stringify({ access_features: 'foo' }));
55
- console.error = jest.fn();
57
+ log.error = jest.fn();
56
58
 
57
59
  await expect(
58
60
  checkForAccess(publicationDomain, accessFeatures)
@@ -95,7 +97,7 @@ describe('/get_vstoken', () => {
95
97
 
96
98
  it('should fail on runtime validation', async () => {
97
99
  fetch.mockResponseOnce(JSON.stringify({ access_features: 'foo' }));
98
- console.error = jest.fn();
100
+ log.error = jest.fn();
99
101
 
100
102
  await expect(getVstoken(publicationDomain)).rejects.toThrow(
101
103
  'Expected { status: "success"; cookie: string; access_features: string[]; }, but was incompatible'
@@ -139,7 +141,7 @@ describe('/non_user_access', () => {
139
141
 
140
142
  it('should fail on runtime validation', async () => {
141
143
  fetch.mockResponseOnce(JSON.stringify({ vstoken_cookie: 3 }));
142
- console.error = jest.fn();
144
+ log.error = jest.fn();
143
145
 
144
146
  await expect(getNonUserAccess(publicationDomain)).rejects.toThrow(
145
147
  'Expected { status: "success"; vstoken_cookie: string; uuid: string; access_features: string[]; }, but was incompatible'
@@ -1,3 +1,4 @@
1
+ /* eslint-disable no-console */
1
2
  import {
2
3
  Array,
3
4
  Literal,
@@ -7,6 +8,7 @@ import {
7
8
  Number,
8
9
  Union,
9
10
  } from 'runtypes';
11
+ import log from '../utils/log';
10
12
 
11
13
  export type AccessFeatures = string[];
12
14
 
@@ -62,7 +64,7 @@ export const checkForAccess = (
62
64
  try {
63
65
  return CheckAccessForPaperSchema.check(json);
64
66
  } catch (error) {
65
- console.error('Invalid schema', error);
67
+ log.error('Invalid schema', error);
66
68
  throw error;
67
69
  }
68
70
  });
@@ -81,7 +83,7 @@ export const getVstoken = (publicationDomain: string): Promise<GetVstoken> =>
81
83
  try {
82
84
  return GetVstokenSchema.check(json);
83
85
  } catch (error) {
84
- console.error('Invalid schema', error);
86
+ log.error('Invalid schema', error);
85
87
  throw error;
86
88
  }
87
89
  });
@@ -104,7 +106,7 @@ export const getNonUserAccess = (
104
106
  try {
105
107
  return GetNonUserAccessSchema.check(json);
106
108
  } catch (error) {
107
- console.error('Invalid schema', error);
109
+ log.error('Invalid schema', error);
108
110
  throw error;
109
111
  }
110
112
  });
@@ -1,18 +1,20 @@
1
1
  import { Record, Static, String } from 'runtypes';
2
+ import log from '../utils/log';
2
3
 
3
- const SessionSchema = Record({
4
+ const ServiceSessionSchema = Record({
4
5
  user_name: String,
5
6
  tracking_key: String,
6
7
  });
7
8
 
8
- export const Session = Record({
9
+ export const InternalSessionSchema = Record({
9
10
  name: String,
10
11
  trackingKey: String,
11
12
  });
13
+
12
14
  // eslint-disable-next-line @typescript-eslint/no-redeclare
13
- export type Session = Static<typeof Session>;
15
+ export type Session = Static<typeof InternalSessionSchema>;
14
16
 
15
- const mapSession = (session: Static<typeof SessionSchema>): Session => ({
17
+ const mapSession = (session: Static<typeof ServiceSessionSchema>): Session => ({
16
18
  name: session.user_name,
17
19
  trackingKey: session.tracking_key,
18
20
  });
@@ -30,9 +32,9 @@ export const getCurrentSession = async (): Promise<Session> =>
30
32
  })
31
33
  .then((json) => {
32
34
  try {
33
- return mapSession(SessionSchema.check(json));
35
+ return mapSession(ServiceSessionSchema.check(json));
34
36
  } catch (error) {
35
- console.error('Invalid schema', error);
37
+ log.error('Invalid schema', error);
36
38
  throw error;
37
39
  }
38
40
  });
package/src/utils/log.ts CHANGED
@@ -1,7 +1,34 @@
1
- // TODO: Actually support logging in some form..
1
+ import mercury from '../services/mercury';
2
+
3
+ export type Logger = {
4
+ debug: (message: string | any, ...extra: any[]) => void;
5
+ info: (message: string | any, ...extra: any[]) => void;
6
+ warn: (message: string | any, ...extra: any[]) => void;
7
+ error: (message: string | any, ...extra: any[]) => void;
8
+ };
9
+
10
+ let logger: Logger;
11
+
12
+ export const setLogger = (engine: Logger) => {
13
+ logger = engine;
14
+ };
15
+
16
+ const getLogger = () => logger || mercury;
17
+
18
+ /* export default {
19
+ debug: getLogger().debug,
20
+ info: getLogger().info,
21
+ warn: getLogger().warn,
22
+ error: getLogger().error,
23
+ }; */
24
+
2
25
  export default {
26
+ // eslint-disable-next-line no-console
3
27
  debug: console.debug,
4
- info: console.log,
28
+ // eslint-disable-next-line no-console
29
+ info: console.info,
30
+ // eslint-disable-next-line no-console
5
31
  warn: console.warn,
32
+ // eslint-disable-next-line no-console
6
33
  error: console.error,
7
34
  };