Skip to content

Commit e22ed3a

Browse files
authored
chore: Style code (#11)
* chore: code optimization
1 parent c7742d3 commit e22ed3a

File tree

4 files changed

+80
-71
lines changed

4 files changed

+80
-71
lines changed

src/EventRecorder.ts

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,6 @@ export class EventRecorder {
1111
private timer: NodeJS.Timer;
1212
private readonly dispatch: Promise<void>;
1313

14-
set flushInterval(value: number) {
15-
clearInterval(this.timer);
16-
this.timer = setInterval(() => this.flush(), value);
17-
}
18-
19-
get accessQueue(): IAccessEvent[] {
20-
return this.sendAccessQueue;
21-
}
22-
23-
get eventQueue(): (AccessEvent | CustomEvent | ClickEvent | PageViewEvent)[] {
24-
return this.sendEventQueue;
25-
}
26-
2714
constructor(
2815
clientSdkKey: string,
2916
eventsUrl: string,
@@ -39,6 +26,19 @@ export class EventRecorder {
3926
this.dispatch = this.startDispatch();
4027
}
4128

29+
set flushInterval(value: number) {
30+
clearInterval(this.timer);
31+
this.timer = setInterval(() => this.flush(), value);
32+
}
33+
34+
get accessQueue(): IAccessEvent[] {
35+
return this.sendAccessQueue;
36+
}
37+
38+
get eventQueue(): (AccessEvent | CustomEvent | ClickEvent | PageViewEvent)[] {
39+
return this.sendEventQueue;
40+
}
41+
4242
public recordAccessEvent(accessEvent: IAccessEvent): void {
4343
if (this.closed) {
4444
console.warn("Trying to push access record to a closed EventProcessor, omitted");
@@ -158,27 +158,28 @@ class AsyncBlockingQueue<T> {
158158
this.promises = [];
159159
}
160160

161-
private add() {
162-
this.promises.push(new Promise(resolve => {
163-
this.resolvers.push(resolve);
164-
}));
165-
}
166-
167-
enqueue(t: T) {
161+
public enqueue(t: T) {
168162
if (!this.resolvers.length) {
169163
this.add();
170164
}
171165
this.resolvers.shift()?.(t);
172166
}
173167

174-
dequeue(): Promise<T> | undefined {
168+
public dequeue(): Promise<T> | undefined {
175169
if (!this.promises.length) {
176170
this.add();
177171
}
178172
return this.promises.shift();
179173
}
180174

181-
isEmpty() {
175+
public isEmpty() {
182176
return !this.promises.length;
183177
}
178+
179+
private add() {
180+
this.promises.push(new Promise(resolve => {
181+
this.resolvers.push(resolve);
182+
}));
183+
}
184+
184185
}

src/FeatureProbe.ts

Lines changed: 37 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ const STATUS = {
2323
ERROR: "error",
2424
};
2525

26+
const REFRESH_INTERVAL = 1000;
27+
const TIMEOUT_INTERVAL = 10000;
28+
2629
/**
2730
* You can obtainan a client of FeatureProbe,
2831
* which provides access to all of the SDK's functionality.
@@ -54,8 +57,8 @@ class FeatureProbe extends TinyEmitter {
5457
realtimePath,
5558
clientSdkKey,
5659
user,
57-
refreshInterval = 1000,
58-
timeoutInterval = 10000,
60+
refreshInterval = REFRESH_INTERVAL,
61+
timeoutInterval = TIMEOUT_INTERVAL,
5962
enableAutoReporting = true,
6063
}: FPConfig) {
6164
super();
@@ -98,6 +101,29 @@ class FeatureProbe extends TinyEmitter {
98101
}
99102
}
100103

104+
public static newForTest(toggles: { [key: string]: boolean }): FeatureProbe {
105+
const fp = new FeatureProbe({
106+
remoteUrl: "http://127.0.0.1:4000",
107+
clientSdkKey: "_",
108+
user: new FPUser(),
109+
timeoutInterval: 1000,
110+
});
111+
const _toggles: { [key: string]: FPDetail } = {};
112+
for (const key in toggles) {
113+
const value = toggles[key];
114+
_toggles[key] = {
115+
value: value,
116+
ruleIndex: null,
117+
variationIndex: null,
118+
version: 0,
119+
reason: "",
120+
};
121+
}
122+
fp.toggles = _toggles;
123+
fp.successInitialized();
124+
return fp;
125+
}
126+
101127
/**
102128
* Start the FeatureProbe client.
103129
*/
@@ -339,29 +365,6 @@ class FeatureProbe extends TinyEmitter {
339365
});
340366
}
341367

342-
static newForTest(toggles: { [key: string]: boolean }): FeatureProbe {
343-
const fp = new FeatureProbe({
344-
remoteUrl: "http://127.0.0.1:4000",
345-
clientSdkKey: "_",
346-
user: new FPUser(),
347-
timeoutInterval: 1000,
348-
});
349-
const _toggles: { [key: string]: FPDetail } = {};
350-
for (const key in toggles) {
351-
const value = toggles[key];
352-
_toggles[key] = {
353-
value: value,
354-
ruleIndex: null,
355-
variationIndex: null,
356-
version: 0,
357-
reason: "",
358-
};
359-
}
360-
fp.toggles = _toggles;
361-
fp.successInitialized();
362-
return fp;
363-
}
364-
365368
private connectSocket() {
366369
const socket = io(this.realtimeUrl, {
367370
path: this.realtimePath,
@@ -395,13 +398,16 @@ class FeatureProbe extends TinyEmitter {
395398
if (typeof v == valueType) {
396399
const timestamp = Date.now();
397400

401+
const DEFAULT_VARIATION_INDEX = -1;
402+
const DEFAULT_VERSION = 0;
403+
398404
this.eventRecorder?.recordAccessEvent({
399405
time: timestamp,
400406
key: key,
401407
value: detail.value,
402-
index: detail.variationIndex ?? -1,
403-
version: detail.version ?? 0,
404-
reason: detail.reason
408+
index: detail.variationIndex ?? DEFAULT_VARIATION_INDEX,
409+
version: detail.version ?? DEFAULT_VERSION,
410+
reason: detail.reason,
405411
});
406412

407413
if (detail.trackAccessEvents) {
@@ -411,9 +417,9 @@ class FeatureProbe extends TinyEmitter {
411417
user: this.getUser().getKey(),
412418
key: key,
413419
value: detail.value,
414-
variationIndex: detail.variationIndex ?? -1,
420+
variationIndex: detail.variationIndex ?? DEFAULT_VARIATION_INDEX,
415421
ruleIndex: detail.ruleIndex ?? null,
416-
version: detail.version ?? 0,
422+
version: detail.version ?? DEFAULT_VERSION,
417423
});
418424
}
419425

@@ -494,7 +500,7 @@ class FeatureProbe extends TinyEmitter {
494500
"Content-Type": "application/json",
495501
UA: getPlatform()?.UA,
496502
}, {
497-
user: userParam
503+
user: userParam,
498504
}, (json: unknown) => {
499505
if (this.status !== STATUS.ERROR) {
500506
this.toggles = json as { [key: string]: FPDetail; } | undefined;

src/autoReportEvents.ts

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,17 @@ import { FPUser } from ".";
33
import { EventRecorder } from "./EventRecorder";
44
import { ClickEvent, IEvent, IEventValue, PageViewEvent } from "./types";
55

6+
const WATCH_URL_CHANGE_INTERVAL = 300;
7+
68
// Reference: https://github.com/sindresorhus/escape-string-regexp
79
function escapeStringRegexp(string: string): string {
8-
if (typeof string !== 'string') {
9-
throw new TypeError('Expected a string');
10-
}
10+
if (typeof string !== 'string') {
11+
throw new TypeError('Expected a string');
12+
}
1113

12-
return string
13-
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
14-
.replace(/-/g, '\\x2d');
14+
return string
15+
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
16+
.replace(/-/g, '\\x2d');
1517
}
1618

1719
/**
@@ -54,7 +56,7 @@ export default function reportEvents(
5456
clientSdkKey: string,
5557
user: FPUser,
5658
getEventsUrl: string,
57-
eventRecorder: EventRecorder
59+
eventRecorder: EventRecorder,
5860
): void {
5961
let previousUrl: string = window.location.href;
6062
let currentUrl;
@@ -100,9 +102,8 @@ export default function reportEvents(
100102
function getClickEvents(event: MouseEvent, clickEvents: IEventValue[]) {
101103
const matchedEvents = [];
102104

103-
for (let i = 0; i < clickEvents.length; i++) {
105+
for (const clickEvent of clickEvents) {
104106
let target = event.target;
105-
const clickEvent = clickEvents[i];
106107
const selector = clickEvent.selector;
107108

108109
const elements = selector && document.querySelectorAll(selector);
@@ -152,8 +153,8 @@ export default function reportEvents(
152153
if (clickEvents.length > 0) {
153154
cb = function(event: MouseEvent) {
154155
const result = getClickEvents(event, clickEvents);
155-
for (let i = 0; i < result.length; i++) {
156-
sendEvents('click', result[i]);
156+
for (const event of result) {
157+
sendEvents('click', event);
157158
}
158159
};
159160

@@ -196,7 +197,7 @@ export default function reportEvents(
196197
*/
197198
setInterval(() => {
198199
watchUrlChange();
199-
}, 300);
200+
}, WATCH_URL_CHANGE_INTERVAL);
200201

201202
/**
202203
* Get events data from Server API

test/autoReportEvents.test.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { FetchMock } from "jest-fetch-mock";
66
import * as data from "./fixtures/events.json";
77

88
const _fetch = fetch as FetchMock;
9+
const FLUSH_INTERVAL = 10000;
910

1011
beforeEach(() => {});
1112

@@ -17,19 +18,19 @@ test("report events", (done) => {
1718
_fetch.mockResponseOnce(JSON.stringify(data));
1819
const clientSdkKey = 'clientSdkKey';
1920
const eventsUrl = 'http://featureprobe.io/server/event';
20-
const recorder = new EventRecorder(clientSdkKey, eventsUrl, 10000);
21+
const recorder = new EventRecorder(clientSdkKey, eventsUrl, FLUSH_INTERVAL);
2122
const user = new FPUser('11111').with("city", "2");
23+
const DELAY = 100;
2224

2325
reportEvents(clientSdkKey, user, eventsUrl, recorder);
2426

25-
2627
setTimeout(() => {
2728
document.body.click();
2829
expect(recorder.eventQueue.length).toBe(3);
29-
expect(recorder.eventQueue[0].kind).toBe('pageview');
30-
expect(recorder.eventQueue[1].kind).toBe('pageview');
31-
expect(recorder.eventQueue[2].kind).toBe('click');
30+
expect(recorder.eventQueue.shift()?.kind).toBe('pageview');
31+
expect(recorder.eventQueue.shift()?.kind).toBe('pageview');
32+
expect(recorder.eventQueue.shift()?.kind).toBe('click');
3233
done();
33-
}, 100);
34+
}, DELAY);
3435
});
3536

0 commit comments

Comments
 (0)