@amedia/user 0.13.25 → 0.13.27
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.
- package/@types/amedia-frontend-rpc.d.ts +11 -0
- package/@types/browserid.d.ts +4 -0
- package/checkVersion.js +12 -0
- package/dist/actions/authorization.d.ts +5 -5
- package/dist/autologin/index.d.ts +4 -0
- package/dist/clients/europa.d.ts +3 -7
- package/dist/clients/mercuryLog.d.ts +5 -4
- package/dist/index.d.ts +78 -35
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/dist/janitor/jobs/daxsubCookie.d.ts +2 -1
- package/dist/lib/PaywallUnlockRequest.d.ts +1 -1
- package/dist/lib/UserDataRequest.d.ts +1 -1
- package/dist/lib/rpc.d.ts +5 -5
- package/dist/utils/customEventWrapper.d.ts +5 -3
- package/dist/utils/debouncer.d.ts +26 -0
- package/dist/utils/debouncer.spec.d.ts +1 -0
- package/dist/utils/deepEquals.d.ts +0 -3
- package/dist/utils/log.d.ts +4 -4
- package/dist/utils/queue.d.ts +2 -2
- package/dist/utils/type.d.ts +6 -0
- package/eik.json +1 -1
- package/package.json +4 -3
- package/src/actions/authorization.spec.ts +13 -9
- package/src/actions/authorization.ts +7 -5
- package/src/autologin/index.spec.ts +3 -3
- package/src/autologin/index.ts +6 -1
- package/src/cache/index.spec.ts +2 -2
- package/src/cache/index.ts +1 -2
- package/src/clients/europa.spec.ts +11 -16
- package/src/clients/europa.ts +47 -41
- package/src/clients/mercuryLog.ts +22 -12
- package/src/clients/pluto.spec.ts +4 -3
- package/src/eventHandlers/state.spec.ts +2 -2
- package/src/eventHandlers/storage.spec.ts +2 -2
- package/src/eventHandlers/userAttributes.spec.ts +2 -2
- package/src/index-authentcation.spec.ts +1 -1
- package/src/index-storage.spec.ts +3 -3
- package/src/index-subscription.spec.ts +1 -1
- package/src/janitor/jobs/accessCookieRefresher.spec.ts +8 -2
- package/src/janitor/jobs/daxsubCookie.spec.ts +8 -2
- package/src/janitor/jobs/daxsubCookie.ts +4 -3
- package/src/lib/PaywallUnlockRequest.spec.ts +12 -12
- package/src/lib/PaywallUnlockRequest.ts +6 -3
- package/src/lib/UserDataRequest.spec.ts +3 -2
- package/src/lib/UserDataRequest.ts +4 -4
- package/src/lib/rpc.ts +7 -9
- package/src/store/index.ts +2 -0
- package/src/utils/customEventWrapper.ts +6 -6
- package/src/utils/debouncer.spec.ts +257 -0
- package/src/utils/debouncer.ts +103 -0
- package/src/utils/deepEquals.ts +12 -11
- package/src/utils/getOrUpdate.ts +1 -1
- package/src/utils/log.spec.ts +4 -4
- package/src/utils/log.ts +24 -13
- package/src/utils/queue.ts +4 -4
- package/src/utils/type.ts +19 -0
- package/tsconfig.eslint.json +2 -0
- package/tsconfig.json +2 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { State, UserAttributes } from '../types';
|
|
2
2
|
declare class UserDataRequest<UA extends UserAttributes, S extends {
|
|
3
3
|
[index: string]: unknown;
|
|
4
|
-
}, Attributes extends Array<keyof UA>, Namespaces extends Array<string>, SubscribeResponse extends
|
|
4
|
+
}, Attributes extends Array<keyof UA>, Namespaces extends Array<string>, SubscribeResponse extends Record<string, object> = {
|
|
5
5
|
state: State;
|
|
6
6
|
}> {
|
|
7
7
|
private attributes?;
|
package/dist/lib/rpc.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
userAuthenticated: (
|
|
4
|
-
}
|
|
5
|
-
export declare const getRPCClient: () =>
|
|
1
|
+
import { RPCclient } from '@amedia/frontend-rpc';
|
|
2
|
+
interface LocalRPCclient extends RPCclient {
|
|
3
|
+
userAuthenticated: (isLoggedIn: boolean) => void;
|
|
4
|
+
}
|
|
5
|
+
export declare const getRPCClient: () => LocalRPCclient;
|
|
6
6
|
export {};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
declare let rootElement: Window | Element;
|
|
2
|
+
export declare const setRootElement: (element: typeof rootElement) => void;
|
|
2
3
|
/**
|
|
3
4
|
* This listener MUST be used by all listeners in ../eventHandlers
|
|
4
5
|
* We want to ensure that only _one_ instance of this package actually
|
|
@@ -6,12 +7,13 @@ export declare const setRootElement: (element: any) => void;
|
|
|
6
7
|
* @param type
|
|
7
8
|
* @param listener
|
|
8
9
|
*/
|
|
9
|
-
export declare const listenWithExclusivity: <T extends keyof WindowEventMap>(type: T, listener: (this:
|
|
10
|
+
export declare const listenWithExclusivity: <T extends keyof WindowEventMap>(type: T, listener: (this: typeof rootElement, ev: WindowEventMap[T]) => void) => void;
|
|
10
11
|
/**
|
|
11
12
|
* Use this for response listeners. (../index.ts) where we want
|
|
12
13
|
* all updates with data - no matter who sent the actual request
|
|
13
14
|
* @param type
|
|
14
15
|
* @param listener
|
|
15
16
|
*/
|
|
16
|
-
export declare const listenForAllEvents: <T extends keyof WindowEventMap>(type: T, listener: (this:
|
|
17
|
+
export declare const listenForAllEvents: <T extends keyof WindowEventMap>(type: T, listener: (this: typeof rootElement, ev: WindowEventMap[T]) => void) => void;
|
|
17
18
|
export declare const dispatch: <T extends Event>(event: T) => void;
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Debouncer can be used when we want a clean way to say 'I want to fetch this and that, and once it's done,
|
|
3
|
+
* resolve my promise', but instead of the fetch being performed right away, we want to wait for more users to
|
|
4
|
+
* request other stuff. This will keep us from performing lots of individual fetches to the backend.
|
|
5
|
+
*
|
|
6
|
+
* Our main use case is a standard publication front page where one component on the page requests the euucp namespace
|
|
7
|
+
* from Europa, and then another component requests the privacy_preferences namespace. Instead of the Europa client
|
|
8
|
+
* calling two fetches to the server, one for euucp and another for privacy_preferences, we want the Debouncer to
|
|
9
|
+
* aggregate these calls into one call to the backend, that requests both euucp AND privacy_preferences, so the response
|
|
10
|
+
* to both components will be both namespaces (which the Europa client can filter before it actually reaches the
|
|
11
|
+
* component).
|
|
12
|
+
*/
|
|
13
|
+
declare class Debouncer<ParamsType, ResultType> {
|
|
14
|
+
private timeoutMs;
|
|
15
|
+
private defaultParams;
|
|
16
|
+
private paramAccumulator;
|
|
17
|
+
private workload;
|
|
18
|
+
private timer;
|
|
19
|
+
private params;
|
|
20
|
+
private queue;
|
|
21
|
+
constructor(timeoutMs: number, defaultParams: ParamsType, paramAccumulator: (previousParams: ParamsType, newParams: ParamsType) => ParamsType, workload: (params: ParamsType) => Promise<ResultType>);
|
|
22
|
+
perform(newParams: ParamsType): Promise<ResultType>;
|
|
23
|
+
static stringListParamsAccumulator(accumulatedParams: string[], newParams: string[]): string[];
|
|
24
|
+
static stringMapParamsAccumulator(previousParams: Record<string, any>, newParams: Record<string, any>): Record<string, any>;
|
|
25
|
+
}
|
|
26
|
+
export default Debouncer;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/utils/log.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
export declare type Logger = {
|
|
2
|
-
debug: (message: string | Error, context?:
|
|
3
|
-
info: (message: string | Error, context?:
|
|
4
|
-
warn: (message: string | Error, context?:
|
|
5
|
-
error: (message: string | Error, context?:
|
|
2
|
+
debug: (message: string | Error, context?: any) => void;
|
|
3
|
+
info: (message: string | Error, context?: any) => void;
|
|
4
|
+
warn: (message: string | Error, context?: any) => void;
|
|
5
|
+
error: (message: string | Error, context?: any) => void;
|
|
6
6
|
};
|
|
7
7
|
export declare const setLogger: (engine: Logger) => void;
|
|
8
8
|
declare const _default: Logger;
|
package/dist/utils/queue.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
declare const _default: {
|
|
2
2
|
add: (key: string, promiseCallbacks: {
|
|
3
|
-
resolve: (
|
|
3
|
+
resolve: (arg0?: any) => void;
|
|
4
4
|
reject: (reason?: any) => void;
|
|
5
5
|
}) => void;
|
|
6
6
|
getAll: (key: string) => {
|
|
7
|
-
resolve: (
|
|
7
|
+
resolve: (arg0?: any) => void;
|
|
8
8
|
reject: (reason?: any) => void;
|
|
9
9
|
}[];
|
|
10
10
|
peekQueueSize: (key: string) => number;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare const isFunction: (argument: unknown) => argument is Function;
|
|
2
|
+
export declare const isRecord: (argument: unknown) => argument is Record<string, unknown>;
|
|
3
|
+
export declare const isError: (argument: unknown) => argument is Error;
|
|
4
|
+
export declare const isString: (argument: unknown) => argument is string;
|
|
5
|
+
export declare const isNumber: (argument: unknown) => argument is number;
|
|
6
|
+
export declare const isBoolean: (argument: unknown) => argument is boolean;
|
package/eik.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amedia/user",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.27",
|
|
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)",
|
|
@@ -13,11 +13,13 @@
|
|
|
13
13
|
"build": "npm install && node build.js",
|
|
14
14
|
"typings": "tsc",
|
|
15
15
|
"eik:package": "run-p typings lint && npm run test && npm run build && eik package",
|
|
16
|
-
"prepublishOnly": "run-p typings lint && npm run test && npm run build"
|
|
16
|
+
"prepublishOnly": "node checkVersion.js && run-p typings lint && npm run test && npm run build",
|
|
17
|
+
"postpublish": "eik package"
|
|
17
18
|
},
|
|
18
19
|
"dependencies": {
|
|
19
20
|
"@amedia/browserid": "^0.1.6",
|
|
20
21
|
"@amedia/frontend-rpc": "^0.0.12",
|
|
22
|
+
"deep-copy-ts": "^0.5.0",
|
|
21
23
|
"runtypes": "^6.3.2",
|
|
22
24
|
"ts-deepmerge": "^1.0.8"
|
|
23
25
|
},
|
|
@@ -28,7 +30,6 @@
|
|
|
28
30
|
"@types/convict": "^6.1.1",
|
|
29
31
|
"@types/dexie": "^1.3.1",
|
|
30
32
|
"@types/jest": "^26.0.24",
|
|
31
|
-
"@types/lodash": "^4.14.172",
|
|
32
33
|
"@typescript-eslint/eslint-plugin": "^4.29.1",
|
|
33
34
|
"esbuild": "^0.12.19",
|
|
34
35
|
"eslint": "^7.32.0",
|
|
@@ -20,11 +20,12 @@ import * as authentication from './authentication';
|
|
|
20
20
|
import { setRootElement } from '../utils/customEventWrapper';
|
|
21
21
|
import { removeAllCookies } from '../lib/cookie';
|
|
22
22
|
import restoreAllMocks = jest.restoreAllMocks;
|
|
23
|
+
import { AccessFeatures } from '../clients/jupiter';
|
|
23
24
|
|
|
24
25
|
const publicationDomain = 'www.avisnavn.no';
|
|
25
26
|
|
|
26
27
|
beforeEach(() => {
|
|
27
|
-
setRootElement(new Document());
|
|
28
|
+
setRootElement(new Document().createElement('div'));
|
|
28
29
|
restoreAllMocks();
|
|
29
30
|
removeAllCookies();
|
|
30
31
|
jest.spyOn(cookie, 'setCookie');
|
|
@@ -113,9 +114,9 @@ describe('hasAccess', () => {
|
|
|
113
114
|
});
|
|
114
115
|
});
|
|
115
116
|
|
|
116
|
-
let cookieResponse;
|
|
117
|
+
let cookieResponse: any;
|
|
117
118
|
|
|
118
|
-
function itReturnsCookieResponse(success, accessFeatures) {
|
|
119
|
+
function itReturnsCookieResponse(success: any, accessFeatures: AccessFeatures) {
|
|
119
120
|
it(`returns cookie response with success = ${success}`, () => {
|
|
120
121
|
expect(cookieResponse.success).toEqual(success);
|
|
121
122
|
});
|
|
@@ -164,7 +165,7 @@ function itSetsVstoken2Cookie() {
|
|
|
164
165
|
});
|
|
165
166
|
}
|
|
166
167
|
|
|
167
|
-
function mockGetUserAccess(status, accessFeatures) {
|
|
168
|
+
function mockGetUserAccess(status: any, accessFeatures: AccessFeatures) {
|
|
168
169
|
beforeEach(async () => {
|
|
169
170
|
jest.spyOn(jupiter, 'getUserAccess').mockResolvedValue({
|
|
170
171
|
status,
|
|
@@ -174,15 +175,18 @@ function mockGetUserAccess(status, accessFeatures) {
|
|
|
174
175
|
});
|
|
175
176
|
}
|
|
176
177
|
|
|
177
|
-
function getUserAccessSucceeds(accessFeatures) {
|
|
178
|
+
function getUserAccessSucceeds(accessFeatures: AccessFeatures) {
|
|
178
179
|
mockGetUserAccess('success', accessFeatures);
|
|
179
180
|
}
|
|
180
181
|
|
|
181
|
-
function getUserAccessFails(accessFeatures) {
|
|
182
|
+
function getUserAccessFails(accessFeatures: AccessFeatures) {
|
|
182
183
|
mockGetUserAccess('failure', accessFeatures);
|
|
183
184
|
}
|
|
184
185
|
|
|
185
|
-
function mockGetNonUserAccessSucceeds(
|
|
186
|
+
function mockGetNonUserAccessSucceeds(
|
|
187
|
+
status: any,
|
|
188
|
+
accessFeatures: AccessFeatures
|
|
189
|
+
) {
|
|
186
190
|
beforeEach(async () => {
|
|
187
191
|
jest.spyOn(jupiter, 'getNonUserAccess').mockResolvedValue({
|
|
188
192
|
status,
|
|
@@ -193,11 +197,11 @@ function mockGetNonUserAccessSucceeds(status, accessFeatures) {
|
|
|
193
197
|
});
|
|
194
198
|
}
|
|
195
199
|
|
|
196
|
-
function getNonUserAccessSucceeds(accessFeatures) {
|
|
200
|
+
function getNonUserAccessSucceeds(accessFeatures: AccessFeatures) {
|
|
197
201
|
mockGetNonUserAccessSucceeds('success', accessFeatures);
|
|
198
202
|
}
|
|
199
203
|
|
|
200
|
-
function getNonUserAccessFails(accessFeatures) {
|
|
204
|
+
function getNonUserAccessFails(accessFeatures: AccessFeatures) {
|
|
201
205
|
mockGetNonUserAccessSucceeds('failure', accessFeatures);
|
|
202
206
|
}
|
|
203
207
|
|
|
@@ -38,7 +38,7 @@ export const hasAccess = (
|
|
|
38
38
|
).length > 0;
|
|
39
39
|
|
|
40
40
|
export const setUserAccessCookie = async (
|
|
41
|
-
publicationDomain
|
|
41
|
+
publicationDomain: string
|
|
42
42
|
): Promise<SetCookieResponse> => {
|
|
43
43
|
const vstoken = await getUserAccess(publicationDomain);
|
|
44
44
|
if (vstoken.status === 'success') {
|
|
@@ -56,7 +56,7 @@ export const setUserAccessCookie = async (
|
|
|
56
56
|
};
|
|
57
57
|
|
|
58
58
|
export const setNonUserAccessCookie = async (
|
|
59
|
-
publicationDomain
|
|
59
|
+
publicationDomain: string
|
|
60
60
|
): Promise<SetCookieResponse> => {
|
|
61
61
|
const vstoken2 = await getNonUserAccess(publicationDomain);
|
|
62
62
|
if (vstoken2.status === 'success') {
|
|
@@ -69,7 +69,7 @@ export const setNonUserAccessCookie = async (
|
|
|
69
69
|
};
|
|
70
70
|
|
|
71
71
|
export const setAccessCookies = async (
|
|
72
|
-
publicationDomain
|
|
72
|
+
publicationDomain: string
|
|
73
73
|
): Promise<SetCookieResponse> => {
|
|
74
74
|
const setters: Array<Promise<SetCookieResponse>> = [];
|
|
75
75
|
setters.push(
|
|
@@ -99,7 +99,7 @@ export const setAccessCookies = async (
|
|
|
99
99
|
);
|
|
100
100
|
};
|
|
101
101
|
|
|
102
|
-
export const setHasPerformedPaywallReload = (requestedUrl
|
|
102
|
+
export const setHasPerformedPaywallReload = (requestedUrl?: string): void => {
|
|
103
103
|
const expires = new Date();
|
|
104
104
|
expires.setTime(expires.getTime() + 2 * 60 * 1000); // Add two minutes
|
|
105
105
|
|
|
@@ -110,6 +110,8 @@ export const setHasPerformedPaywallReload = (requestedUrl?): void => {
|
|
|
110
110
|
);
|
|
111
111
|
};
|
|
112
112
|
|
|
113
|
-
export const hasRecentlyPerformedPaywallReload = (
|
|
113
|
+
export const hasRecentlyPerformedPaywallReload = (
|
|
114
|
+
requestedUrl?: string
|
|
115
|
+
): boolean =>
|
|
114
116
|
getCookie('aid-paywall-reload-performed') ===
|
|
115
117
|
(requestedUrl || getCurrentUrl());
|
|
@@ -31,7 +31,7 @@ function itShouldCallThirdPartyCookieStrategy() {
|
|
|
31
31
|
});
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
function itShouldNavigateToAutoLogin(context) {
|
|
34
|
+
function itShouldNavigateToAutoLogin(context: string) {
|
|
35
35
|
it(`should navigate to auto with context ${context}`, async () => {
|
|
36
36
|
expect(location.navigateTo).toHaveBeenCalledWith(
|
|
37
37
|
`https://www.aid.no/aid/logg_inn/auto?context=auto_login_${context}&requestedUrl=https%3A%2F%2Fwww.avisnavn.no%2Fabo%2F%3Fquery%3Dparam`
|
|
@@ -102,7 +102,7 @@ describe('attemptAutoLoginJob', () => {
|
|
|
102
102
|
});
|
|
103
103
|
|
|
104
104
|
describe('when in iframe (Dr. Edition)', () => {
|
|
105
|
-
let originalTop;
|
|
105
|
+
let originalTop: Window;
|
|
106
106
|
beforeEach(async () => {
|
|
107
107
|
originalTop = global.top;
|
|
108
108
|
// @ts-ignore
|
|
@@ -199,7 +199,7 @@ describe('attemptPaywallAutoLogin', () => {
|
|
|
199
199
|
});
|
|
200
200
|
|
|
201
201
|
describe('when in iframe (Dr. Edition)', () => {
|
|
202
|
-
let originalTop;
|
|
202
|
+
let originalTop: Window;
|
|
203
203
|
beforeEach(async () => {
|
|
204
204
|
originalTop = global.top;
|
|
205
205
|
// @ts-ignore
|
package/src/autologin/index.ts
CHANGED
|
@@ -4,6 +4,11 @@ import { navigateTo } from '../utils/location';
|
|
|
4
4
|
import { getCookie, removeCookie, setCookie } from '../lib/cookie';
|
|
5
5
|
import UserDataRequest from '../lib/UserDataRequest';
|
|
6
6
|
|
|
7
|
+
export type Strategies = Array<{
|
|
8
|
+
name: string;
|
|
9
|
+
handler: () => Promise<boolean>;
|
|
10
|
+
}>;
|
|
11
|
+
|
|
7
12
|
const AUTOLOGIN_COOKIE = 'has-tried-autologin';
|
|
8
13
|
export const AUTOLOGIN_COOKIE_TTL = 60000; // One minute
|
|
9
14
|
|
|
@@ -30,7 +35,7 @@ function hasAlreadyAttemptedAutoLogin() {
|
|
|
30
35
|
return false;
|
|
31
36
|
}
|
|
32
37
|
|
|
33
|
-
const attemptAutologin = async (strategies) => {
|
|
38
|
+
const attemptAutologin = async (strategies: Strategies) => {
|
|
34
39
|
if (inIframe()) {
|
|
35
40
|
// Avoid auto-login on preview for dr edition.
|
|
36
41
|
return;
|
package/src/cache/index.spec.ts
CHANGED
package/src/cache/index.ts
CHANGED
|
@@ -30,8 +30,7 @@ const get = async <T extends RuntypeBase>(
|
|
|
30
30
|
return Promise.resolve();
|
|
31
31
|
}
|
|
32
32
|
try {
|
|
33
|
-
|
|
34
|
-
return typedData as T;
|
|
33
|
+
return validator.check(cacheEntry.data);
|
|
35
34
|
} catch (error) {
|
|
36
35
|
log.error(error, { cacheData: cacheEntry.data });
|
|
37
36
|
remove(key);
|
|
@@ -44,7 +44,7 @@ describe('Europa', () => {
|
|
|
44
44
|
const updated = await updateNamespace('user_info', newUserInfo).then(() =>
|
|
45
45
|
cache.get('europa', EuropaSchema)
|
|
46
46
|
);
|
|
47
|
-
expect(updated).toMatchObject({
|
|
47
|
+
expect(updated).toMatchObject({ user_info: newUserInfo });
|
|
48
48
|
expect(fetch).toHaveBeenCalledTimes(3);
|
|
49
49
|
});
|
|
50
50
|
|
|
@@ -53,7 +53,7 @@ describe('Europa', () => {
|
|
|
53
53
|
|
|
54
54
|
await saveNamespace('euucp', { x: 'x' });
|
|
55
55
|
expect(cache.get('europa', EuropaSchema)).resolves.toMatchObject({
|
|
56
|
-
|
|
56
|
+
euucp: { x: 'x' },
|
|
57
57
|
}); // expect something in cache
|
|
58
58
|
|
|
59
59
|
await clearLocalCache();
|
|
@@ -73,7 +73,7 @@ describe('Europa', () => {
|
|
|
73
73
|
// expect x and y
|
|
74
74
|
expect(await cache.get('europa', EuropaSchema)).toEqual(
|
|
75
75
|
expect.objectContaining({
|
|
76
|
-
|
|
76
|
+
euucp: data,
|
|
77
77
|
})
|
|
78
78
|
);
|
|
79
79
|
|
|
@@ -81,7 +81,7 @@ describe('Europa', () => {
|
|
|
81
81
|
// expect only y
|
|
82
82
|
expect(await cache.get('europa', EuropaSchema)).toEqual(
|
|
83
83
|
expect.objectContaining({
|
|
84
|
-
|
|
84
|
+
euucp: { y: 'y' },
|
|
85
85
|
})
|
|
86
86
|
);
|
|
87
87
|
});
|
|
@@ -98,7 +98,7 @@ describe('Europa', () => {
|
|
|
98
98
|
});
|
|
99
99
|
|
|
100
100
|
describe('getNamespaces', () => {
|
|
101
|
-
let response;
|
|
101
|
+
let response: any;
|
|
102
102
|
describe('with cold cache', () => {
|
|
103
103
|
describe('with one namespace', () => {
|
|
104
104
|
const data = { euucp: { x: 'x' } };
|
|
@@ -125,7 +125,7 @@ describe('getNamespaces', () => {
|
|
|
125
125
|
describe('when doing sequence of calls for different namespaces', () => {
|
|
126
126
|
const data = { euucp: { x: 'x' } };
|
|
127
127
|
const data2 = { user_info: { a: 'a' } };
|
|
128
|
-
let response2;
|
|
128
|
+
let response2: any;
|
|
129
129
|
beforeEach(async () => {
|
|
130
130
|
fetch.mockResponseOnce(JSON.stringify({ namespaces: data }));
|
|
131
131
|
fetch.mockResponseOnce(JSON.stringify({ namespaces: data2 }));
|
|
@@ -141,10 +141,11 @@ describe('getNamespaces', () => {
|
|
|
141
141
|
describe('when doing sequence of calls for different namespaces before first response returns', () => {
|
|
142
142
|
const data = { euucp: { x: 'x' } };
|
|
143
143
|
const data2 = { user_info: { a: 'a' } };
|
|
144
|
-
let response2;
|
|
144
|
+
let response2: any;
|
|
145
145
|
beforeEach(async () => {
|
|
146
|
-
fetch.mockResponseOnce(
|
|
147
|
-
|
|
146
|
+
fetch.mockResponseOnce(
|
|
147
|
+
JSON.stringify({ namespaces: { ...data, ...data2 } })
|
|
148
|
+
);
|
|
148
149
|
const futureEuucp = getNamespaces(['euucp']);
|
|
149
150
|
response2 = await getNamespaces(['user_info']);
|
|
150
151
|
response = await futureEuucp;
|
|
@@ -161,13 +162,7 @@ describe('getNamespaces', () => {
|
|
|
161
162
|
describe('with one namespace in cache', () => {
|
|
162
163
|
const data = { euucp: { x: 'x' } };
|
|
163
164
|
beforeEach(() => {
|
|
164
|
-
cache.set(
|
|
165
|
-
'europa',
|
|
166
|
-
{
|
|
167
|
-
namespaces: data,
|
|
168
|
-
},
|
|
169
|
-
100000
|
|
170
|
-
);
|
|
165
|
+
cache.set('europa', data, 100000);
|
|
171
166
|
});
|
|
172
167
|
|
|
173
168
|
describe('when requesting cached namespace', () => {
|
package/src/clients/europa.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Unknown, Dictionary, String, Static } from 'runtypes';
|
|
2
2
|
|
|
3
3
|
import cache from '../cache';
|
|
4
4
|
import getOrUpdate from '../utils/getOrUpdate';
|
|
5
5
|
import log from '../utils/log';
|
|
6
|
+
import Debouncer from '../utils/debouncer';
|
|
6
7
|
|
|
7
8
|
const CACHE_DURATION = 5 * 60000; // 5 minutes
|
|
9
|
+
const DEBOUNCE_WAIT_TIME = 20; // 20ms wait before actually calling Europa
|
|
8
10
|
|
|
9
|
-
export const EuropaSchema =
|
|
11
|
+
export const EuropaSchema = Dictionary(Unknown, String);
|
|
10
12
|
|
|
11
13
|
export const clearLocalCache = () => cache.remove('europa');
|
|
12
14
|
|
|
@@ -20,23 +22,22 @@ const doFetch = (url: string, method: string = 'GET', body?: Object) =>
|
|
|
20
22
|
},
|
|
21
23
|
});
|
|
22
24
|
|
|
23
|
-
function mergeCache(
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
),
|
|
32
|
-
|
|
25
|
+
function mergeCache(
|
|
26
|
+
cachedData: Static<typeof EuropaSchema> | void,
|
|
27
|
+
newData: Static<typeof EuropaSchema>
|
|
28
|
+
) {
|
|
29
|
+
return Object.entries(newData).reduce(
|
|
30
|
+
(mergedNamespaces, [namespace, data]) => ({
|
|
31
|
+
...mergedNamespaces,
|
|
32
|
+
[namespace]: data,
|
|
33
|
+
}),
|
|
34
|
+
cachedData || {}
|
|
35
|
+
);
|
|
33
36
|
}
|
|
34
37
|
|
|
35
38
|
const updateNamespaceInCache = async (namespace: string, data: Object) => {
|
|
36
39
|
const cachedData = await cache.get('europa', EuropaSchema);
|
|
37
|
-
const updatedData = mergeCache(cachedData, {
|
|
38
|
-
namespaces: { [namespace]: data },
|
|
39
|
-
});
|
|
40
|
+
const updatedData = mergeCache(cachedData, { [namespace]: data });
|
|
40
41
|
return cache.set('europa', updatedData, Date.now() + CACHE_DURATION);
|
|
41
42
|
};
|
|
42
43
|
|
|
@@ -52,6 +53,27 @@ export const updateNamespace = async (namespace: string, data: Object) => {
|
|
|
52
53
|
return updateNamespaceInCache(namespace, data);
|
|
53
54
|
};
|
|
54
55
|
|
|
56
|
+
const debouncer = new Debouncer<string[], typeof EuropaSchema>(
|
|
57
|
+
DEBOUNCE_WAIT_TIME,
|
|
58
|
+
[],
|
|
59
|
+
Debouncer.stringListParamsAccumulator,
|
|
60
|
+
(params) =>
|
|
61
|
+
doFetch(`/api/europa/v1/me/${params.join(',')}`).then(async (response) => {
|
|
62
|
+
const body = await response.text();
|
|
63
|
+
if (!response.ok) {
|
|
64
|
+
// TODO we should possibly extend Europa to say what param we're missing so we can ignore missing aid.session cookie
|
|
65
|
+
if (response.status !== 400) {
|
|
66
|
+
log.error(
|
|
67
|
+
`Could not get namespaces for: ${params}, status: ${response.status}`,
|
|
68
|
+
{ response, body }
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
return {};
|
|
72
|
+
}
|
|
73
|
+
return JSON.parse(body).namespaces;
|
|
74
|
+
})
|
|
75
|
+
);
|
|
76
|
+
|
|
55
77
|
export const getNamespaces = async <
|
|
56
78
|
S extends { [namespace: string]: { [index: string]: unknown } },
|
|
57
79
|
Namespaces extends Array<keyof S>
|
|
@@ -64,48 +86,32 @@ export const getNamespaces = async <
|
|
|
64
86
|
}
|
|
65
87
|
|
|
66
88
|
let missingNamespaces = namespaces as string[];
|
|
67
|
-
const cachedData = await cache.get('europa', EuropaSchema)
|
|
89
|
+
const cachedData = (await cache.get('europa', EuropaSchema)) || {
|
|
90
|
+
namespaces: {},
|
|
91
|
+
};
|
|
68
92
|
if (!options.ignoreCache) {
|
|
69
93
|
missingNamespaces = (
|
|
70
94
|
cachedData
|
|
71
95
|
? namespaces.filter(
|
|
72
96
|
(namespace) =>
|
|
73
|
-
!Object.keys(cachedData
|
|
97
|
+
!Object.keys(cachedData).includes(namespace as string)
|
|
74
98
|
)
|
|
75
99
|
: namespaces
|
|
76
100
|
) as string[];
|
|
77
101
|
if (cachedData && missingNamespaces.length === 0) {
|
|
78
102
|
// Yay! Everything we need is in the cache!
|
|
79
|
-
return Promise.resolve(
|
|
80
|
-
cachedData.namespaces as Pick<S, Namespaces[number]>
|
|
81
|
-
);
|
|
103
|
+
return Promise.resolve(cachedData as Pick<S, Namespaces[number]>);
|
|
82
104
|
}
|
|
83
105
|
}
|
|
84
106
|
|
|
85
|
-
const fetchedNamespaces = await
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const body = await response.text();
|
|
89
|
-
if (!response.ok) {
|
|
90
|
-
// TODO we should possibly extend Europa to say what param we're missing so we can ignore missing aid.session cookie
|
|
91
|
-
if (response.status !== 400) {
|
|
92
|
-
log.error(
|
|
93
|
-
`Could not get namespaces for: ${namespaces}, status: ${response.status}`,
|
|
94
|
-
{ response, body }
|
|
95
|
-
);
|
|
96
|
-
}
|
|
97
|
-
return { namespaces: {} };
|
|
98
|
-
}
|
|
99
|
-
return JSON.parse(body);
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
Object.entries(fetchedNamespaces.namespaces).forEach(
|
|
103
|
-
([namespace, fetchedNamespace]) =>
|
|
104
|
-
updateNamespaceInCache(namespace, fetchedNamespace as Object)
|
|
107
|
+
const fetchedNamespaces = await debouncer.perform(missingNamespaces);
|
|
108
|
+
Object.entries(fetchedNamespaces).forEach(([namespace, fetchedNamespace]) =>
|
|
109
|
+
updateNamespaceInCache(namespace, fetchedNamespace as Object)
|
|
105
110
|
);
|
|
106
111
|
|
|
107
112
|
return Promise.resolve(
|
|
108
|
-
|
|
113
|
+
// @ts-ignore
|
|
114
|
+
Object.entries(mergeCache(cachedData, fetchedNamespaces))
|
|
109
115
|
.filter(([namespace]) => namespaces.includes(namespace))
|
|
110
116
|
.reduce(
|
|
111
117
|
(returnedEntries, [namespace, data]) => ({
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { getCurrentHostname, getCurrentUrl } from '../utils/url';
|
|
2
|
+
import { isBoolean, isNumber, isString } from '../utils/type';
|
|
3
|
+
|
|
4
|
+
type Context = Record<string, unknown>;
|
|
2
5
|
|
|
3
6
|
/**
|
|
4
7
|
* Extracted from mercury.tsx so other calls to mercury can log properly
|
|
@@ -15,22 +18,29 @@ function postLog(url: string, query: { [index: string]: any }) {
|
|
|
15
18
|
};
|
|
16
19
|
fetch(url, options).then((res) => {
|
|
17
20
|
if (!res.ok) {
|
|
18
|
-
|
|
21
|
+
console.error(
|
|
22
|
+
`Failed to send log to backend: Error, status: ${res.status}, text: ${res.statusText}`
|
|
23
|
+
);
|
|
19
24
|
}
|
|
20
25
|
});
|
|
21
26
|
}
|
|
22
27
|
|
|
23
|
-
const backendLog = (level: string, message: string, context:
|
|
24
|
-
const internalContext = {};
|
|
28
|
+
const backendLog = (level: string, message: string, context: Context) => {
|
|
29
|
+
const internalContext: Context = {};
|
|
25
30
|
Object.keys(context).forEach((key) => {
|
|
26
|
-
|
|
27
|
-
|
|
31
|
+
const currentContext = context[key];
|
|
32
|
+
if (
|
|
33
|
+
isString(currentContext) ||
|
|
34
|
+
isNumber(currentContext) ||
|
|
35
|
+
isBoolean(currentContext)
|
|
36
|
+
) {
|
|
37
|
+
internalContext[key] = currentContext;
|
|
28
38
|
return;
|
|
29
39
|
}
|
|
30
40
|
try {
|
|
31
|
-
internalContext[key] = JSON.stringify(
|
|
32
|
-
} catch
|
|
33
|
-
internalContext[key] =
|
|
41
|
+
internalContext[key] = JSON.stringify(currentContext);
|
|
42
|
+
} catch {
|
|
43
|
+
internalContext[key] = currentContext;
|
|
34
44
|
}
|
|
35
45
|
});
|
|
36
46
|
const extendedContext = {
|
|
@@ -43,13 +53,13 @@ const backendLog = (level: string, message: string, context: Object) => {
|
|
|
43
53
|
};
|
|
44
54
|
|
|
45
55
|
const log = {
|
|
46
|
-
error: (message: string, context:
|
|
56
|
+
error: (message: string, context: Context) =>
|
|
47
57
|
backendLog('error', message, context),
|
|
48
|
-
warn: (message: string, context:
|
|
58
|
+
warn: (message: string, context: Context) =>
|
|
49
59
|
backendLog('warn', message, context),
|
|
50
|
-
info: (message: string, context:
|
|
60
|
+
info: (message: string, context: Context) =>
|
|
51
61
|
backendLog('info', message, context),
|
|
52
|
-
debug: (message: string, context:
|
|
62
|
+
debug: (message: string, context: Context) =>
|
|
53
63
|
backendLog('debug', message, context),
|
|
54
64
|
};
|
|
55
65
|
|