Skip to content

Commit 0f9985a

Browse files
committed
fix: support timestamps like in segment
1 parent 542c93f commit 0f9985a

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

packages/logging/src/analytics-helpers.ts

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
11
import fs from 'fs';
22
import path from 'path';
3-
import type { IdentifyParams as SegmentIndetifyParams } from '@segment/analytics-node';
3+
import type {
4+
IdentifyParams as SegmentIdentifyParams,
5+
TrackParams as SegmentTrackParams,
6+
} from '@segment/analytics-node';
47

5-
export type MongoshAnalyticsIdentity = SegmentIndetifyParams;
8+
type Timestamp = SegmentTrackParams['timestamp'];
9+
10+
export type MongoshAnalyticsIdentity = SegmentIdentifyParams & {
11+
anonymousId: string;
12+
};
613

714
export type AnalyticsIdentifyMessage = MongoshAnalyticsIdentity & {
815
traits: {
916
platform: string;
1017
session_id: string;
1118
device_id: string;
12-
} & SegmentIndetifyParams['traits'];
13-
timestamp?: Date & SegmentIndetifyParams['timestamp'];
19+
} & SegmentIdentifyParams['traits'];
20+
timestamp?: SegmentIdentifyParams['timestamp'];
1421
};
1522

1623
export type AnalyticsTrackMessage = MongoshAnalyticsIdentity & {
@@ -20,7 +27,7 @@ export type AnalyticsTrackMessage = MongoshAnalyticsIdentity & {
2027
session_id: string;
2128
[key: string]: any;
2229
};
23-
timestamp?: Date;
30+
timestamp?: Timestamp;
2431
};
2532

2633
/**
@@ -88,10 +95,14 @@ type AnalyticsEventsQueueItem =
8895
| ['identify', Parameters<MongoshAnalytics['identify']>]
8996
| ['track', Parameters<MongoshAnalytics['track']>];
9097

91-
function addTimestamp<T extends { timestamp?: Date }>(
98+
function addTimestamp<T extends { timestamp?: Timestamp }>(
9299
message: T
93-
): T & { timestamp: Date } {
94-
return { ...message, timestamp: message.timestamp ?? new Date() };
100+
): T & { timestamp: Timestamp } {
101+
const timestampDate =
102+
message.timestamp instanceof Date || message.timestamp === undefined
103+
? message.timestamp
104+
: new Date(message.timestamp);
105+
return { ...message, timestamp: timestampDate };
95106
}
96107

97108
/**
@@ -271,8 +282,7 @@ export class ThrottledAnalytics implements MongoshAnalytics {
271282
throw new Error('Identify can only be called once per user session');
272283
}
273284

274-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
275-
this.currentUserId = message.userId ?? message.anonymousId!;
285+
this.currentUserId = message.userId ?? message.anonymousId;
276286

277287
this.restorePromise = this.restoreThrottleState().then((enabled) => {
278288
if (!enabled) {

0 commit comments

Comments
 (0)