@amedia/user 0.7.1 → 0.7.3

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.
@@ -0,0 +1,168 @@
1
+ import { Partial, String } from 'runtypes';
2
+ import cache from '../cache';
3
+ import getOrUpdate from './getOrUpdate';
4
+ import queue from './queue';
5
+ import spyOn = jest.spyOn;
6
+ import resetAllMocks = jest.resetAllMocks;
7
+
8
+ const schema = Partial({ field: String, extraField: String });
9
+
10
+ beforeEach(async () => {
11
+ resetAllMocks();
12
+ await cache.clear();
13
+ });
14
+ describe('getOrUpdate', () => {
15
+ it('should fetch if no cache is available', () => {
16
+ const fetcher = jest.fn().mockResolvedValue({
17
+ ttl: 0,
18
+ data: { field: 'fetchedValue' },
19
+ });
20
+ expect(getOrUpdate('client', schema, fetcher))
21
+ .resolves.toEqual({
22
+ field: 'fetchedValue',
23
+ })
24
+ .then(expect(fetcher).toHaveBeenCalled);
25
+ });
26
+
27
+ it('should add to cache after fetching', async () => {
28
+ const cacheSpy = spyOn(cache, 'set');
29
+ await getOrUpdate(
30
+ 'client',
31
+ schema,
32
+ jest.fn().mockResolvedValue({
33
+ ttl: 10,
34
+ data: { field: 'value' },
35
+ })
36
+ );
37
+ expect(cacheSpy).toHaveBeenCalledWith('client', { field: 'value' }, 10);
38
+ });
39
+
40
+ it('should use cache if available instead of fetching', () => {
41
+ spyOn(cache, 'get').mockResolvedValue({
42
+ field: 'cachedValue',
43
+ });
44
+ const fetcher = jest.fn().mockResolvedValue({
45
+ ttl: 0,
46
+ data: { field: 'fetchedValue' },
47
+ });
48
+ expect(getOrUpdate('client', schema, fetcher))
49
+ .resolves.toEqual({ field: 'cachedValue' })
50
+ .then(expect(fetcher).not.toHaveBeenCalled);
51
+ });
52
+
53
+ it('should allow cache qualifier to override valid result', () => {
54
+ spyOn(cache, 'get').mockResolvedValue({
55
+ field: 'cachedValue',
56
+ });
57
+ const fetcher = jest.fn().mockResolvedValue({
58
+ ttl: 0,
59
+ data: { field: 'fetchedValue' },
60
+ });
61
+ const qualifier = jest.fn().mockReturnValue(false);
62
+ expect(getOrUpdate('client', schema, fetcher, qualifier))
63
+ .resolves.toEqual({ field: 'fetchedValue' })
64
+ .then(expect(fetcher).toHaveBeenCalled)
65
+ .then(() =>
66
+ expect(qualifier).toHaveBeenCalledWith({ field: 'cachedValue' })
67
+ );
68
+ });
69
+
70
+ it('should append to existing cache if any', async () => {
71
+ spyOn(cache, 'get').mockResolvedValue({
72
+ field: 'cachedValue',
73
+ });
74
+ const cacheSetSpy = spyOn(cache, 'set');
75
+ await getOrUpdate(
76
+ 'client',
77
+ schema,
78
+ () => Promise.resolve({ ttl: 0, data: { extraField: 'extraValue' } }),
79
+ () => false
80
+ );
81
+ expect(cacheSetSpy).toHaveBeenCalledWith(
82
+ 'client',
83
+ { field: 'cachedValue', extraField: 'extraValue' },
84
+ 0
85
+ );
86
+ });
87
+
88
+ it('should resolve queue on cached data', (done) => {
89
+ let resolvePromise: Function;
90
+ const promise = new Promise((resolve) => {
91
+ resolvePromise = resolve;
92
+ });
93
+ spyOn(cache, 'get').mockReturnValue(promise);
94
+
95
+ expect(
96
+ Promise.all([
97
+ getOrUpdate('client', schema, jest.fn()),
98
+ getOrUpdate('client', schema, jest.fn()),
99
+ getOrUpdate('client', schema, jest.fn()),
100
+ ])
101
+ )
102
+ .resolves.toEqual([
103
+ { field: 'value' },
104
+ { field: 'value' },
105
+ { field: 'value' },
106
+ ])
107
+ .then(done);
108
+
109
+ expect(queue.peekQueueSize('client')).toEqual(3);
110
+
111
+ // @ts-ignore It has been assigned. Promise
112
+ resolvePromise({ field: 'value' });
113
+ });
114
+
115
+ it('should resolve queue on fetched data', (done) => {
116
+ let resolvePromise: Function;
117
+ const promise = new Promise((resolve) => {
118
+ resolvePromise = resolve;
119
+ });
120
+
121
+ spyOn(cache, 'get').mockResolvedValue(null);
122
+
123
+ expect(
124
+ Promise.all([
125
+ getOrUpdate('client', schema, jest.fn().mockReturnValue(promise)),
126
+ getOrUpdate('client', schema, jest.fn()),
127
+ getOrUpdate('client', schema, jest.fn()),
128
+ ])
129
+ )
130
+ .resolves.toEqual([
131
+ { field: 'value' },
132
+ { field: 'value' },
133
+ { field: 'value' },
134
+ ])
135
+ .then(() => expect(queue.peekQueueSize('client')).toEqual(0))
136
+ .then(done);
137
+
138
+ expect(queue.peekQueueSize('client')).toEqual(3);
139
+
140
+ // @ts-ignore It has been assigned. Promise
141
+ resolvePromise({ ttl: 0, data: { field: 'value' } });
142
+ });
143
+
144
+ it('should reject queue if fetching fails', (done) => {
145
+ let rejectPromise: Function;
146
+ const promise = new Promise((resolve, reject) => {
147
+ rejectPromise = reject;
148
+ });
149
+
150
+ spyOn(cache, 'get').mockResolvedValue(null);
151
+
152
+ const a = jest.fn().mockReturnValue(promise);
153
+ const b = jest.fn();
154
+ const c = jest.fn();
155
+
156
+ expect(getOrUpdate('client', schema, a)).rejects.toEqual(undefined);
157
+ expect(getOrUpdate('client', schema, b)).rejects.toEqual(undefined);
158
+ expect(getOrUpdate('client', schema, c))
159
+ .rejects.toEqual(undefined)
160
+ .then(() => expect(queue.peekQueueSize('client')).toEqual(0))
161
+ .then(done);
162
+
163
+ expect(queue.peekQueueSize('client')).toEqual(3);
164
+
165
+ // @ts-ignore It has been assigned. Promise
166
+ rejectPromise();
167
+ });
168
+ });
@@ -7,10 +7,31 @@ export type DataFetcherWithCacheTTL<T extends Runtype> = Promise<{
7
7
  data: Static<T>;
8
8
  }>;
9
9
 
10
+ const mergeCache = (oldCache: unknown, newCache: unknown): unknown => {
11
+ // Since we cannot know how to deal with duplicates when newCache is array
12
+ // always return newCache
13
+ if (!oldCache || Array.isArray(newCache)) {
14
+ return newCache;
15
+ }
16
+
17
+ // TODO: Possible bug? :)
18
+ if (!newCache) {
19
+ return oldCache;
20
+ }
21
+
22
+ if (typeof oldCache === 'object' && typeof newCache === 'object') {
23
+ return { ...oldCache, ...newCache };
24
+ }
25
+
26
+ // Cannot merge (eg type is string etc)
27
+ return newCache;
28
+ };
29
+
10
30
  export default function getOrUpdate<T extends Runtype>(
11
31
  key: string,
12
32
  schema: T,
13
- fetch: () => DataFetcherWithCacheTTL<T>
33
+ fetch: () => DataFetcherWithCacheTTL<T>,
34
+ cacheQualifier?: (cacheData: Static<T>) => boolean
14
35
  ): Promise<Static<T>> {
15
36
  return new Promise((resolve, reject) => {
16
37
  queue.add(key, { resolve, reject });
@@ -19,7 +40,7 @@ export default function getOrUpdate<T extends Runtype>(
19
40
  }
20
41
 
21
42
  cache.get(key, schema).then((cacheResponse) => {
22
- if (cacheResponse) {
43
+ if (cacheResponse && (!cacheQualifier || cacheQualifier(cacheResponse))) {
23
44
  queue.getAll(key).forEach((promise) => {
24
45
  promise.resolve(cacheResponse);
25
46
  });
@@ -27,7 +48,10 @@ export default function getOrUpdate<T extends Runtype>(
27
48
  }
28
49
  fetch()
29
50
  .then((res) => {
30
- cache.set(key, res.data, res.ttl);
51
+ const newCache = cacheResponse
52
+ ? mergeCache(cacheResponse, res.data)
53
+ : res.data;
54
+ cache.set(key, newCache, res.ttl);
31
55
  queue.getAll(key).forEach((promise) => {
32
56
  promise.resolve(res.data);
33
57
  });
@@ -1,4 +0,0 @@
1
- /**
2
- * @jest-environment jsdom
3
- */
4
- export {};
@@ -1,12 +0,0 @@
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>;
@@ -1,29 +0,0 @@
1
- import { Array, Literal, Record, Static, String, Number, Union } from 'runtypes';
2
- export declare type AccessFeatures = string[];
3
- export declare const CheckAccessForPaperSchema: Record<{
4
- status: Literal<"success">;
5
- access: Union<[Literal<"granted">, Literal<"denied">]>;
6
- publication: Record<{
7
- id: Number;
8
- domain: String;
9
- }, false>;
10
- access_features: Array<String, false>;
11
- }, false>;
12
- export declare type CheckAccessForPaper = Static<typeof CheckAccessForPaperSchema>;
13
- declare const GetVstokenSchema: Record<{
14
- status: Literal<"success">;
15
- cookie: String;
16
- access_features: Array<String, false>;
17
- }, false>;
18
- export declare type GetVstoken = Static<typeof GetVstokenSchema>;
19
- declare const GetNonUserAccessSchema: Record<{
20
- status: Literal<"success">;
21
- vstoken_cookie: String;
22
- uuid: String;
23
- access_features: Array<String, false>;
24
- }, false>;
25
- export declare type GetNonUserAccess = Static<typeof GetNonUserAccessSchema>;
26
- export declare const checkForAccess: (publicationDomain: string, accessFeatures: AccessFeatures) => Promise<CheckAccessForPaper>;
27
- export declare const getVstoken: (publicationDomain: string) => Promise<GetVstoken>;
28
- export declare const getNonUserAccess: (publicationDomain: string) => Promise<GetNonUserAccess>;
29
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1,18 +0,0 @@
1
- declare const log: {
2
- error: (message: string, context: {
3
- [index: string]: any;
4
- }) => void;
5
- warn: (message: string, context: {
6
- [index: string]: any;
7
- }) => void;
8
- info: (message: string, context: {
9
- [index: string]: any;
10
- }) => void;
11
- debug: (message: string, context: {
12
- [index: string]: any;
13
- }) => void;
14
- };
15
- export declare class UserDeactivatedError extends Error {
16
- }
17
- export declare const activateSubscription: (accessFeature: string) => Promise<boolean>;
18
- export default log;
@@ -1,4 +0,0 @@
1
- /**
2
- * @jest-environment jsdom
3
- */
4
- export {};
@@ -1,22 +0,0 @@
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 {};
@@ -1 +0,0 @@
1
- export {};
@@ -1,8 +0,0 @@
1
- import { Record, Static, String } from 'runtypes';
2
- export declare const InternalSessionSchema: Record<{
3
- name: String;
4
- trackingKey: String;
5
- }, false>;
6
- export declare type Session = Static<typeof InternalSessionSchema>;
7
- export declare const getCurrentSession: () => Promise<Session>;
8
- export declare const removeSession: (domain: string) => Promise<void>;
@@ -1 +0,0 @@
1
- export {};
@@ -1,13 +0,0 @@
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;
@@ -1 +0,0 @@
1
- export {};