@amedia/user 0.5.2 → 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.
- package/README.md +2 -2
- package/cloudbuild.json +29 -0
- package/cop.json +8 -0
- package/dist/actions/authentication.d.ts +1 -1
- package/dist/actions/preferences.d.ts +9 -0
- package/dist/actions/preferences.spec.d.ts +1 -0
- package/dist/cache/index.d.ts +3 -2
- package/dist/clients/europa.d.ts +12 -0
- package/dist/clients/europa.spec.d.ts +1 -0
- package/dist/clients/jupiter.d.ts +29 -0
- package/dist/clients/jupiter.spec.d.ts +1 -0
- package/dist/clients/mercury.d.ts +18 -0
- package/dist/clients/mercury.spec.d.ts +4 -0
- package/dist/clients/nebula.d.ts +22 -0
- package/dist/clients/nebula.spec.d.ts +1 -0
- package/dist/clients/pluto.d.ts +8 -0
- package/dist/clients/pluto.spec.d.ts +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/lib/rpc.d.ts +6 -1
- package/dist/services/europa.d.ts +12 -0
- package/dist/services/europa.spec.d.ts +1 -0
- package/dist/services/nebula.d.ts +22 -0
- package/dist/services/nebula.spec.d.ts +1 -0
- package/dist/store/store.d.ts +13 -0
- package/dist/store/store.spec.d.ts +1 -0
- package/dist/types.d.ts +7 -0
- package/dist/utils/getOrUpdate.d.ts +3 -0
- package/package.json +4 -3
- package/src/actions/authentication.ts +2 -2
- package/src/actions/authorization.ts +4 -7
- package/src/actions/preferences.spec.ts +54 -0
- package/src/actions/preferences.ts +69 -0
- package/src/actions/userData.ts +2 -0
- package/src/cache/index.spec.ts +7 -2
- package/src/cache/index.ts +4 -3
- package/src/clients/europa.spec.ts +93 -0
- package/src/clients/europa.ts +126 -0
- package/src/clients/jupiter.spec.ts +154 -0
- package/src/{services → clients}/jupiter.ts +0 -1
- package/src/clients/mercury.spec.ts +70 -0
- package/src/clients/nebula.spec.ts +71 -0
- package/src/clients/nebula.ts +51 -0
- package/src/index-authentcation.spec.ts +2 -2
- package/src/index-userdata.spec.ts +11 -11
- package/src/index.ts +4 -3
- package/src/lib/rpc.ts +9 -3
- package/src/store/store.spec.ts +34 -0
- package/src/store/store.ts +46 -0
- package/src/types.ts +8 -0
- package/src/utils/getOrUpdate.ts +41 -0
- package/src/utils/log.ts +2 -1
- package/src/utils/queue.ts +0 -2
- package/src/services/jupiter.spec.ts +0 -150
- package/src/services/mercury.spec.ts +0 -30
- /package/src/{services → clients}/mercury.ts +0 -0
- /package/src/{services → clients}/pluto.spec.ts +0 -0
- /package/src/{services → clients}/pluto.ts +0 -0
package/dist/lib/rpc.d.ts
CHANGED
|
@@ -1 +1,6 @@
|
|
|
1
|
-
|
|
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,12 @@
|
|
|
1
|
+
import { Record, Partial } from 'runtypes';
|
|
2
|
+
export declare const EuropaSchema: Record<{
|
|
3
|
+
namespaces: Partial<{}, false>;
|
|
4
|
+
}, false>;
|
|
5
|
+
export declare const clearLocalCache: () => Promise<void>;
|
|
6
|
+
export declare const updateNamespace: (namespace: string, data: Object) => Promise<void | {}>;
|
|
7
|
+
export declare const getNamespace: (namespace: string, options?: {
|
|
8
|
+
ignoreCache: boolean;
|
|
9
|
+
}) => Promise<any>;
|
|
10
|
+
export declare const saveNamespace: (namespace: string, data: Object) => Promise<any>;
|
|
11
|
+
export declare const getAllNamespaces: () => Promise<{}>;
|
|
12
|
+
export declare const deleteNamespaceKey: (namespace: string, key: string) => Promise<any>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Static, Partial, Dictionary, Unknown, String, Number, Boolean } from 'runtypes';
|
|
2
|
+
declare const InfoSchema: import("runtypes").Intersect<[Dictionary<Unknown, string>, Partial<{
|
|
3
|
+
ad_segments: String;
|
|
4
|
+
ad_segments_user: String;
|
|
5
|
+
age: Number;
|
|
6
|
+
age_user: Number;
|
|
7
|
+
birth_year: String;
|
|
8
|
+
birth_year_user: String;
|
|
9
|
+
gender: String;
|
|
10
|
+
gender_user: String;
|
|
11
|
+
grunnkrets: String;
|
|
12
|
+
grunnkrets_user: String;
|
|
13
|
+
postcode: String;
|
|
14
|
+
postcode_user: String;
|
|
15
|
+
shared_account: Boolean;
|
|
16
|
+
shared_account_user: Boolean;
|
|
17
|
+
user_grouping_number: String;
|
|
18
|
+
user_grouping_number_user: String;
|
|
19
|
+
}, false>]>;
|
|
20
|
+
export declare type Info = Static<typeof InfoSchema>;
|
|
21
|
+
export declare const getInfo: (userKey: string, publicationDomain: string, browserId: string) => Promise<Info>;
|
|
22
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
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
|
+
};
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amedia/user",
|
|
3
|
-
"version": "0.
|
|
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
|
|
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 '../
|
|
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,
|
|
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 '../
|
|
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 =
|
|
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
|
-
|
|
38
|
+
EXPIRES_OFFSET
|
|
42
39
|
);
|
|
43
40
|
queue.getAll(GET_ACCESS_QUEUE_KEY).forEach((promise) => {
|
|
44
41
|
promise.resolve({ access: accessState.access_features });
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import fetch from 'jest-fetch-mock';
|
|
2
|
+
import cache from '../cache';
|
|
3
|
+
import queue from '../utils/queue';
|
|
4
|
+
import { getPrivacyPreferences } from './preferences';
|
|
5
|
+
|
|
6
|
+
fetch.enableMocks();
|
|
7
|
+
|
|
8
|
+
beforeEach(() => {
|
|
9
|
+
fetch.resetMocks();
|
|
10
|
+
cache.clear();
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
const europaResponse = {
|
|
14
|
+
namespaces: {
|
|
15
|
+
privacy_preferences: {
|
|
16
|
+
allow_research_usage: 'true',
|
|
17
|
+
connect_with_surveys: true,
|
|
18
|
+
personalzied_ads: 'false',
|
|
19
|
+
personalized_content: false,
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
describe('privacyPreferences', () => {
|
|
25
|
+
it('should return preferences', async () => {
|
|
26
|
+
fetch.mockResponse(JSON.stringify(europaResponse));
|
|
27
|
+
await getPrivacyPreferences();
|
|
28
|
+
expect(fetch).toHaveBeenCalledTimes(1);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('simultanious call should return same preferences', async () => {
|
|
32
|
+
fetch.mockResponse(JSON.stringify(europaResponse));
|
|
33
|
+
|
|
34
|
+
jest.spyOn(queue, 'add');
|
|
35
|
+
await Promise.all([getPrivacyPreferences(), getPrivacyPreferences()]);
|
|
36
|
+
expect(queue.add).toHaveBeenCalledTimes(2);
|
|
37
|
+
expect(fetch).toHaveBeenCalledTimes(1);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('should use cache if available', async () => {
|
|
41
|
+
fetch.mockResponse(JSON.stringify(europaResponse));
|
|
42
|
+
|
|
43
|
+
jest.spyOn(cache, 'get').mockReturnValue(
|
|
44
|
+
Promise.resolve({
|
|
45
|
+
allowResearchUsage: true,
|
|
46
|
+
connectWithSurveys: true,
|
|
47
|
+
personalziedAds: false,
|
|
48
|
+
personalizedContent: false,
|
|
49
|
+
})
|
|
50
|
+
);
|
|
51
|
+
await Promise.all([getPrivacyPreferences(), getPrivacyPreferences()]);
|
|
52
|
+
expect(fetch).toHaveBeenCalledTimes(0);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { Record, Boolean } from 'runtypes';
|
|
2
|
+
import cache from '../cache';
|
|
3
|
+
import { getNamespace } from '../clients/europa';
|
|
4
|
+
import { UserAttributes, PrivacyPreferences } from '../types';
|
|
5
|
+
import log from '../utils/log';
|
|
6
|
+
import queue from '../utils/queue';
|
|
7
|
+
|
|
8
|
+
const CACHE_DURATION = 5 * 60000; // 5 minutes
|
|
9
|
+
const PRIVACY_PREFERENCES_QUEUE_KEY = 'privacy_preferences_queue';
|
|
10
|
+
const PRIVACY_PREFERENCES_CACHE_KEY = 'privacyPreferences';
|
|
11
|
+
|
|
12
|
+
export const PrivacyPreferencesSchema = Record({
|
|
13
|
+
allowResearchUsage: Boolean,
|
|
14
|
+
connectWithSurveys: Boolean,
|
|
15
|
+
personalizedAds: Boolean,
|
|
16
|
+
personalizedContent: Boolean,
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const toBoolean = (val: string | boolean) => val === 'true' || val === true;
|
|
20
|
+
|
|
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) {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
|
|
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
|
+
}
|
|
37
|
+
|
|
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
|
+
};
|
|
49
|
+
|
|
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
|
+
});
|
|
69
|
+
});
|
package/src/actions/userData.ts
CHANGED
|
@@ -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 = {};
|
package/src/cache/index.spec.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
98
|
+
MOCK_NOW_TIMESTAMP + EXPIRES
|
|
94
99
|
);
|
|
95
100
|
});
|
|
96
101
|
});
|
package/src/cache/index.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
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
|
|
20
|
+
const get = async <T extends RuntypeBase>(
|
|
20
21
|
key: string,
|
|
21
22
|
validator: T
|
|
22
23
|
): Promise<Static<T> | void> => {
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import fetch from 'jest-fetch-mock';
|
|
2
|
+
import cache from '../cache';
|
|
3
|
+
import {
|
|
4
|
+
updateNamespace,
|
|
5
|
+
EuropaSchema,
|
|
6
|
+
clearLocalCache,
|
|
7
|
+
saveNamespace,
|
|
8
|
+
deleteNamespaceKey,
|
|
9
|
+
getNamespace,
|
|
10
|
+
getAllNamespaces,
|
|
11
|
+
} from './europa';
|
|
12
|
+
|
|
13
|
+
fetch.enableMocks();
|
|
14
|
+
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
fetch.resetMocks();
|
|
17
|
+
cache.clear();
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
describe('Europa', () => {
|
|
21
|
+
it('saveNamespace should set namespace and return the new value', async () => {
|
|
22
|
+
const userInfo = { gender: 'U', post_code: 'U' };
|
|
23
|
+
fetch.mockOnce(JSON.stringify(userInfo)); // data to save 'PUT'
|
|
24
|
+
fetch.mockOnce(JSON.stringify({ namespaces: { user_info: userInfo } })); // data retrieved 'GET'
|
|
25
|
+
|
|
26
|
+
const namespaceData = await saveNamespace('user_info', userInfo);
|
|
27
|
+
expect(namespaceData).toMatchObject(userInfo);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('updateNamespace should update namespace', async () => {
|
|
31
|
+
const oldUserInfo = { gender: 'F', post_code: 'U' };
|
|
32
|
+
const newUserInfo = { gender: 'M', post_code: '2150' };
|
|
33
|
+
|
|
34
|
+
fetch.mockOnce(JSON.stringify({})); // initial response // 'PUT'
|
|
35
|
+
fetch.mockOnce(JSON.stringify({ namespaces: { user_info: oldUserInfo } })); // old 'GET'
|
|
36
|
+
fetch.mockOnce(JSON.stringify({ namespaces: { user_info: newUserInfo } })); // updated 'GET'
|
|
37
|
+
|
|
38
|
+
const old = await saveNamespace('user_info', oldUserInfo);
|
|
39
|
+
expect(fetch).toHaveBeenCalledTimes(2);
|
|
40
|
+
expect(old).toMatchObject(oldUserInfo);
|
|
41
|
+
|
|
42
|
+
const updated = await updateNamespace('user_info', newUserInfo).then(() =>
|
|
43
|
+
cache.get('europa', EuropaSchema)
|
|
44
|
+
);
|
|
45
|
+
expect(updated).toMatchObject({ namespaces: { user_info: newUserInfo } });
|
|
46
|
+
expect(fetch).toHaveBeenCalledTimes(3);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('clearLocalCache should remove Europa cache', async () => {
|
|
50
|
+
fetch.mockResponse(JSON.stringify({ namespaces: { euucp: { x: 'x' } } }));
|
|
51
|
+
|
|
52
|
+
await saveNamespace('euucp', { x: 'x' });
|
|
53
|
+
expect(cache.get('europa', EuropaSchema)).resolves.toMatchObject({
|
|
54
|
+
namespaces: { euucp: { x: 'x' } },
|
|
55
|
+
}); // expect something in cache
|
|
56
|
+
|
|
57
|
+
await clearLocalCache();
|
|
58
|
+
expect(cache.get('europa', EuropaSchema)).resolves.toBeUndefined(); // expect cache to be empty
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('deleteNamespaceKey should remove key from europa', async () => {
|
|
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
|
+
|
|
68
|
+
await saveNamespace('euucp', { x: 'x' });
|
|
69
|
+
expect(cache.get('europa', EuropaSchema)).resolves.toMatchObject({
|
|
70
|
+
namespaces: { euucp: { x: 'x', y: 'y' } },
|
|
71
|
+
}); // expect x and y
|
|
72
|
+
|
|
73
|
+
await deleteNamespaceKey('euucp', 'x');
|
|
74
|
+
expect(cache.get('europa', EuropaSchema)).resolves.toMatchObject({
|
|
75
|
+
namespaces: { euucp: { y: 'y' } },
|
|
76
|
+
}); // expect only y
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('getAllNamespaces should return all europa namespaces', () => {
|
|
80
|
+
const namespaceData = {
|
|
81
|
+
euucp: { x: 'x' },
|
|
82
|
+
user_info: { gender: 'M', post_code: 'U' },
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
fetch.mockResponse(JSON.stringify({ namespaces: namespaceData }));
|
|
86
|
+
expect(getAllNamespaces()).resolves.toMatchObject(namespaceData);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('getNamespace should return europa namespace', () => {
|
|
90
|
+
fetch.mockResponse(JSON.stringify({ namespaces: { euucp: { x: 'x' } } }));
|
|
91
|
+
expect(getNamespace('euucp')).resolves.toMatchObject({ x: 'x' });
|
|
92
|
+
});
|
|
93
|
+
});
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { Record, Partial } from 'runtypes';
|
|
2
|
+
|
|
3
|
+
import cache from '../cache';
|
|
4
|
+
import log from '../utils/log';
|
|
5
|
+
|
|
6
|
+
const CACHE_DURATION = 5 * 60000; // 5 minutes
|
|
7
|
+
|
|
8
|
+
export const EuropaSchema = Record({
|
|
9
|
+
namespaces: Partial({}),
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
export const clearLocalCache = () => cache.remove('europa');
|
|
13
|
+
|
|
14
|
+
const doFetch = (url: string, method?: string, body?: Object) =>
|
|
15
|
+
fetch(url, {
|
|
16
|
+
method: method && method,
|
|
17
|
+
body: body && JSON.stringify(body),
|
|
18
|
+
headers: {
|
|
19
|
+
'Content-Type': 'application/json',
|
|
20
|
+
Accept: 'application/json',
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const updateNamespaceInCache = async (namespace: string, data: Object) => {
|
|
25
|
+
const cachedData = await cache.get('europa', EuropaSchema);
|
|
26
|
+
const updatedData = cachedData
|
|
27
|
+
? {
|
|
28
|
+
...cachedData,
|
|
29
|
+
namespaces: { ...cachedData.namespaces, [namespace]: data },
|
|
30
|
+
}
|
|
31
|
+
: { namespaces: { [namespace]: data } };
|
|
32
|
+
|
|
33
|
+
return cache.set('europa', updatedData, Date.now() + CACHE_DURATION);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export const updateNamespace = async (namespace: string, data: Object) => {
|
|
37
|
+
const res = await doFetch(
|
|
38
|
+
`//www.aid.no/api/europa/v1/me/${namespace}`,
|
|
39
|
+
'PATCH',
|
|
40
|
+
data
|
|
41
|
+
);
|
|
42
|
+
if (!res.ok) {
|
|
43
|
+
log.error(
|
|
44
|
+
`Could not get namespace: ${namespace}, status: ${res.status}, statusText: ${res.statusText}`,
|
|
45
|
+
res
|
|
46
|
+
);
|
|
47
|
+
return {};
|
|
48
|
+
}
|
|
49
|
+
return updateNamespaceInCache(namespace, data);
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export const getNamespace = async (
|
|
53
|
+
namespace: string,
|
|
54
|
+
options: { ignoreCache: boolean } = { ignoreCache: false }
|
|
55
|
+
) => {
|
|
56
|
+
if (!options.ignoreCache) {
|
|
57
|
+
const cacheData = await cache.get('europa', EuropaSchema);
|
|
58
|
+
if (cacheData && cacheData.namespaces[namespace]) {
|
|
59
|
+
return cacheData.namespaces[namespace];
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return doFetch(`//www.aid.no/api/europa/v1/me/${namespace}`, 'GET')
|
|
64
|
+
.then((res) => {
|
|
65
|
+
if (!res.ok) {
|
|
66
|
+
log.error(
|
|
67
|
+
`Could not get namespace: ${namespace}, status: ${res.status}, statusText: ${res.statusText}`,
|
|
68
|
+
res
|
|
69
|
+
);
|
|
70
|
+
return {};
|
|
71
|
+
}
|
|
72
|
+
return res.json();
|
|
73
|
+
})
|
|
74
|
+
.then((data) => {
|
|
75
|
+
const validData = EuropaSchema.check(data);
|
|
76
|
+
updateNamespaceInCache(namespace, validData.namespaces[namespace]);
|
|
77
|
+
return validData.namespaces[namespace] || {};
|
|
78
|
+
})
|
|
79
|
+
.catch((error) => {
|
|
80
|
+
log.error(`Could not get namespace: ${namespace}. Error:${error}`);
|
|
81
|
+
return {};
|
|
82
|
+
});
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
export const saveNamespace = (namespace: string, data: Object) =>
|
|
86
|
+
doFetch(`//www.aid.no/api/europa/v1/me/${namespace}`, 'PUT', data)
|
|
87
|
+
.then((res) => {
|
|
88
|
+
if (!res.ok) {
|
|
89
|
+
log.error(
|
|
90
|
+
`Could not get save namespace, namespace:${namespace} status: ${res.status}, statusText: ${res.statusText}`,
|
|
91
|
+
res
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
return {};
|
|
95
|
+
})
|
|
96
|
+
.then(() => getNamespace(namespace, { ignoreCache: true })); // updates cache
|
|
97
|
+
|
|
98
|
+
export const getAllNamespaces = () =>
|
|
99
|
+
doFetch(`//www.aid.no/api/europa/v1/me`)
|
|
100
|
+
.then((res) => {
|
|
101
|
+
if (!res.ok) {
|
|
102
|
+
log.error(
|
|
103
|
+
`Could not get all namespaces, status: ${res.status}, statusText: ${res.statusText}`,
|
|
104
|
+
res
|
|
105
|
+
);
|
|
106
|
+
return {};
|
|
107
|
+
}
|
|
108
|
+
return res.json();
|
|
109
|
+
})
|
|
110
|
+
.then((data) => {
|
|
111
|
+
const europaValidData = EuropaSchema.check(data);
|
|
112
|
+
cache.set('europa', europaValidData, CACHE_DURATION);
|
|
113
|
+
return europaValidData.namespaces;
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
export const deleteNamespaceKey = (namespace: string, key: string) =>
|
|
117
|
+
doFetch(`//www.aid.no/api/europa/v1/me/${namespace}/${key}`, 'DELETE')
|
|
118
|
+
.then((res) => {
|
|
119
|
+
if (!res.ok) {
|
|
120
|
+
log.error(
|
|
121
|
+
`Could not get namespace: ${namespace}, status: ${res.status}, statusText: ${res.statusText}`,
|
|
122
|
+
res
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
})
|
|
126
|
+
.then(() => getNamespace(namespace, { ignoreCache: true })); // updates cache
|