Skip to content

Commit cf2d026

Browse files
Merge pull request #282 from splitio/reuse_isConsumerMode_util
Refactor: rename and reuse some utility functions
2 parents 7fa8de5 + d3e2909 commit cf2d026

File tree

12 files changed

+45
-44
lines changed

12 files changed

+45
-44
lines changed

src/sdkClient/client.ts

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { IEvaluationResult } from '../evaluator/types';
99
import { SplitIO, ImpressionDTO } from '../types';
1010
import { IMPRESSION, IMPRESSION_QUEUEING } from '../logger/constants';
1111
import { ISdkFactoryContext } from '../sdkFactory/types';
12-
import { isStorageSync } from '../trackers/impressionObserver/utils';
12+
import { isConsumerMode } from '../utils/settingsValidation/mode';
1313
import { Method } from '../sync/submitters/types';
1414

1515
const treatmentNotReady = { treatment: CONTROL, label: SDK_NOT_READY };
@@ -28,6 +28,7 @@ function treatmentsNotReady(featureFlagNames: string[]) {
2828
export function clientFactory(params: ISdkFactoryContext): SplitIO.IClient | SplitIO.IAsyncClient {
2929
const { sdkReadinessManager: { readinessManager }, storage, settings, impressionsTracker, eventTracker, telemetryTracker } = params;
3030
const { log, mode } = settings;
31+
const isAsync = isConsumerMode(mode);
3132

3233
function getTreatment(key: SplitIO.SplitKey, featureFlagName: string, attributes: SplitIO.Attributes | undefined, withConfig = false, methodName = GET_TREATMENT) {
3334
const stopTelemetryTracker = telemetryTracker.trackEval(withConfig ? TREATMENT_WITH_CONFIG : TREATMENT);
@@ -43,9 +44,9 @@ export function clientFactory(params: ISdkFactoryContext): SplitIO.IClient | Spl
4344

4445
const evaluation = readinessManager.isReady() || readinessManager.isReadyFromCache() ?
4546
evaluateFeature(log, key, featureFlagName, attributes, storage) :
46-
isStorageSync(settings) ? // If the SDK is not ready, treatment may be incorrect due to having splits but not segments data, or storage is not connected
47-
treatmentNotReady :
48-
Promise.resolve(treatmentNotReady); // Promisify if async
47+
isAsync ? // If the SDK is not ready, treatment may be incorrect due to having splits but not segments data, or storage is not connected
48+
Promise.resolve(treatmentNotReady) :
49+
treatmentNotReady;
4950

5051
return thenable(evaluation) ? evaluation.then((res) => wrapUp(res)) : wrapUp(evaluation);
5152
}
@@ -71,9 +72,9 @@ export function clientFactory(params: ISdkFactoryContext): SplitIO.IClient | Spl
7172

7273
const evaluations = readinessManager.isReady() || readinessManager.isReadyFromCache() ?
7374
evaluateFeatures(log, key, featureFlagNames, attributes, storage) :
74-
isStorageSync(settings) ? // If the SDK is not ready, treatment may be incorrect due to having splits but not segments data, or storage is not connected
75-
treatmentsNotReady(featureFlagNames) :
76-
Promise.resolve(treatmentsNotReady(featureFlagNames)); // Promisify if async
75+
isAsync ? // If the SDK is not ready, treatment may be incorrect due to having splits but not segments data, or storage is not connected
76+
Promise.resolve(treatmentsNotReady(featureFlagNames)) :
77+
treatmentsNotReady(featureFlagNames);
7778

7879
return thenable(evaluations) ? evaluations.then((res) => wrapUp(res)) : wrapUp(evaluations);
7980
}
@@ -100,7 +101,9 @@ export function clientFactory(params: ISdkFactoryContext): SplitIO.IClient | Spl
100101

101102
const evaluations = readinessManager.isReady() || readinessManager.isReadyFromCache() ?
102103
evaluateFeaturesByFlagSets(log, key, flagSetNames, attributes, storage, methodName) :
103-
isStorageSync(settings) ? {} : Promise.resolve({}); // Promisify if async
104+
isAsync ?
105+
Promise.resolve({}) :
106+
{};
104107

105108
return thenable(evaluations) ? evaluations.then((res) => wrapUp(res)) : wrapUp(evaluations);
106109
}

src/sdkClient/clientInputValidation.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import { CONTROL, CONTROL_WITH_CONFIG, GET_TREATMENT, GET_TREATMENTS, GET_TREATM
1616
import { IReadinessManager } from '../readiness/types';
1717
import { MaybeThenable } from '../dtos/types';
1818
import { ISettings, SplitIO } from '../types';
19-
import { isStorageSync } from '../trackers/impressionObserver/utils';
19+
import { isConsumerMode } from '../utils/settingsValidation/mode';
2020
import { validateFlagSets } from '../utils/settingsValidation/splitFilters';
2121

2222
/**
@@ -25,8 +25,8 @@ import { validateFlagSets } from '../utils/settingsValidation/splitFilters';
2525
*/
2626
export function clientInputValidationDecorator<TClient extends SplitIO.IClient | SplitIO.IAsyncClient>(settings: ISettings, client: TClient, readinessManager: IReadinessManager): TClient {
2727

28-
const log = settings.log;
29-
const isSync = isStorageSync(settings);
28+
const { log, mode } = settings;
29+
const isAsync = isConsumerMode(mode);
3030

3131
/**
3232
* Avoid repeating this validations code
@@ -59,7 +59,7 @@ export function clientInputValidationDecorator<TClient extends SplitIO.IClient |
5959
}
6060

6161
function wrapResult<T>(value: T): MaybeThenable<T> {
62-
return isSync ? value : Promise.resolve(value);
62+
return isAsync ? Promise.resolve(value) : value;
6363
}
6464

6565
function getTreatment(maybeKey: SplitIO.SplitKey, maybeFeatureFlagName: string, maybeAttributes?: SplitIO.Attributes) {
@@ -159,7 +159,7 @@ export function clientInputValidationDecorator<TClient extends SplitIO.IClient |
159159
if (isNotDestroyed && key && tt && event && eventValue !== false && properties !== false) { // @ts-expect-error
160160
return client.track(key, tt, event, eventValue, properties, size);
161161
} else {
162-
return isSync ? false : Promise.resolve(false);
162+
return isAsync ? Promise.resolve(false) : false;
163163
}
164164
}
165165

src/sdkManager/index.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { ISplitsCacheAsync, ISplitsCacheSync } from '../storages/types';
66
import { ISdkReadinessManager } from '../readiness/types';
77
import { ISplit } from '../dtos/types';
88
import { ISettings, SplitIO } from '../types';
9-
import { isStorageSync } from '../trackers/impressionObserver/utils';
9+
import { isConsumerMode } from '../utils/settingsValidation/mode';
1010
import { SPLIT_FN_LABEL, SPLITS_FN_LABEL, NAMES_FN_LABEL } from '../utils/constants';
1111

1212
function collectTreatments(splitObject: ISplit) {
@@ -51,8 +51,8 @@ export function sdkManagerFactory<TSplitCache extends ISplitsCacheSync | ISplits
5151
{ readinessManager, sdkStatus }: ISdkReadinessManager,
5252
): TSplitCache extends ISplitsCacheAsync ? SplitIO.IAsyncManager : SplitIO.IManager {
5353

54-
const log = settings.log;
55-
const isSync = isStorageSync(settings);
54+
const { log, mode } = settings;
55+
const isAsync = isConsumerMode(mode);
5656

5757
return objectAssign(
5858
// Proto-linkage of the readiness Event Emitter
@@ -64,7 +64,7 @@ export function sdkManagerFactory<TSplitCache extends ISplitsCacheSync | ISplits
6464
split(featureFlagName: string) {
6565
const splitName = validateSplit(log, featureFlagName, SPLIT_FN_LABEL);
6666
if (!validateIfNotDestroyed(log, readinessManager, SPLIT_FN_LABEL) || !validateIfOperational(log, readinessManager, SPLIT_FN_LABEL) || !splitName) {
67-
return isSync ? null : Promise.resolve(null);
67+
return isAsync ? Promise.resolve(null) : null;
6868
}
6969

7070
const split = splits.getSplit(splitName);
@@ -85,7 +85,7 @@ export function sdkManagerFactory<TSplitCache extends ISplitsCacheSync | ISplits
8585
*/
8686
splits() {
8787
if (!validateIfNotDestroyed(log, readinessManager, SPLITS_FN_LABEL) || !validateIfOperational(log, readinessManager, SPLITS_FN_LABEL)) {
88-
return isSync ? [] : Promise.resolve([]);
88+
return isAsync ? Promise.resolve([]) : [];
8989
}
9090
const currentSplits = splits.getAll();
9191

@@ -98,7 +98,7 @@ export function sdkManagerFactory<TSplitCache extends ISplitsCacheSync | ISplits
9898
*/
9999
names() {
100100
if (!validateIfNotDestroyed(log, readinessManager, NAMES_FN_LABEL) || !validateIfOperational(log, readinessManager, NAMES_FN_LABEL)) {
101-
return isSync ? [] : Promise.resolve([]);
101+
return isAsync ? Promise.resolve([]) : [];
102102
}
103103
const splitNames = splits.getSplitNames();
104104

src/storages/inLocalStorage/SplitsCacheInLocal.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ export class SplitsCacheInLocal extends AbstractSplitsCacheSync {
238238
}
239239

240240
private _checkFilterQuery() {
241-
const { queryString } = this.splitFiltersValidation;
241+
const queryString = this.splitFiltersValidation.queryString;
242242
const queryKey = this.keys.buildSplitsFilterQueryKey();
243243
const currentQueryString = localStorage.getItem(queryKey);
244244

src/storages/inRedis/__tests__/ImpressionCountsCacheInRedis.spec.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// @ts-nocheck
22
import { ImpressionCountsCacheInRedis } from '../ImpressionCountsCacheInRedis';
33
import { truncateTimeFrame } from '../../../utils/time';
4-
import { RedisMock } from '../../../utils/redis/RedisMock';
4+
import { RedisAdapterMock } from './RedisAdapter.mock';
55
import { loggerMock } from '../../../logger/__tests__/sdkLogger.mock';
66
import { RedisAdapter } from '../RedisAdapter';
77

@@ -109,7 +109,7 @@ describe('IMPRESSION COUNTS CACHE IN REDIS', () => {
109109

110110
test('start and stop task', (done) => {
111111

112-
const connection = new RedisMock();
112+
const connection = new RedisAdapterMock();
113113
const refreshRate = 100;
114114
const counter = new ImpressionCountsCacheInRedis(loggerMock, key, connection, undefined, refreshRate);
115115
counter.track('feature1', timestamp, 1);

src/utils/redis/RedisMock.ts renamed to src/storages/inRedis/__tests__/RedisAdapter.mock.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ const IDENTITY_METHODS: string[] = [];
1111
const ASYNC_METHODS = ['rpush', 'hincrby'];
1212
const PIPELINE_METHODS = ['rpush', 'hincrby'];
1313

14-
export class RedisMock {
14+
export class RedisAdapterMock {
1515

16-
private pipelineMethods: any = { exec: jest.fn(asyncFunction) };
16+
private pipelineMethods = { exec: jest.fn(asyncFunction) };
1717

1818
constructor() {
1919
IDENTITY_METHODS.forEach(method => {

src/storages/inRedis/__tests__/UniqueKeysCacheInRedis.spec.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import { UniqueKeysCacheInRedis } from '../UniqueKeysCacheInRedis';
44
import { loggerMock } from '../../../logger/__tests__/sdkLogger.mock';
5-
import { RedisMock } from '../../../utils/redis/RedisMock';
5+
import { RedisAdapterMock } from './RedisAdapter.mock';
66
import { RedisAdapter } from '../RedisAdapter';
77

88
describe('UNIQUE KEYS CACHE IN REDIS', () => {
@@ -104,7 +104,7 @@ describe('UNIQUE KEYS CACHE IN REDIS', () => {
104104
});
105105

106106
test('start and stop task', (done) => {
107-
const connection = new RedisMock();
107+
const connection = new RedisAdapterMock();
108108
const key = 'unique_key_post';
109109
const refreshRate = 100;
110110

src/trackers/eventTracker.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { IEventsHandler, IEventTracker } from './types';
55
import { ISettings, SplitIO } from '../types';
66
import { EVENTS_TRACKER_SUCCESS, ERROR_EVENTS_TRACKER } from '../logger/constants';
77
import { CONSENT_DECLINED, DROPPED, QUEUED } from '../utils/constants';
8-
import { isStorageSync } from './impressionObserver/utils';
8+
import { isConsumerMode } from '../utils/settingsValidation/mode';
99

1010
/**
1111
* Event tracker stores events in cache and pass them to the integrations manager if provided.
@@ -20,8 +20,8 @@ export function eventTrackerFactory(
2020
telemetryCache?: ITelemetryCacheSync | ITelemetryCacheAsync
2121
): IEventTracker {
2222

23-
const log = settings.log;
24-
const isSync = isStorageSync(settings);
23+
const { log, mode } = settings;
24+
const isAsync = isConsumerMode(mode);
2525

2626
function queueEventsCallback(eventData: SplitIO.EventData, tracked: boolean) {
2727
const { eventTypeId, trafficTypeName, key, value, timestamp, properties } = eventData;
@@ -50,7 +50,7 @@ export function eventTrackerFactory(
5050
return {
5151
track(eventData: SplitIO.EventData, size?: number) {
5252
if (settings.userConsent === CONSENT_DECLINED) {
53-
return isSync ? false : Promise.resolve(false);
53+
return isAsync ? Promise.resolve(false) : false;
5454
}
5555

5656
const tracked = eventsCache.track(eventData, size);

src/trackers/impressionObserver/utils.ts

Lines changed: 0 additions & 9 deletions
This file was deleted.

src/utils/settingsValidation/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { merge, get } from '../lang';
2-
import { mode } from './mode';
2+
import { validateMode } from './mode';
33
import { validateSplitFilters } from './splitFilters';
44
import { STANDALONE_MODE, OPTIMIZED, LOCALHOST_MODE, DEBUG } from '../constants';
55
import { validImpressionsMode } from './impressionsMode';
@@ -146,7 +146,7 @@ export function settingsValidation(config: unknown, validationParams: ISettingsV
146146

147147
// ensure a valid SDK mode
148148
// @ts-ignore, modify readonly prop
149-
withDefaults.mode = mode(withDefaults.core.authorizationKey, withDefaults.mode);
149+
withDefaults.mode = validateMode(withDefaults.core.authorizationKey, withDefaults.mode);
150150

151151
// ensure a valid Storage based on mode defined.
152152
// @ts-ignore, modify readonly prop

0 commit comments

Comments
 (0)