({
envName,
bufferWhenNoUser = false,
}: {
envName: EnvName
bufferWhenNoUser?: boolean
})
| 25 | * - Reusing the shared payload builder for consistency |
| 26 | */ |
| 27 | export function createAnalyticsDispatcher({ |
| 28 | envName, |
| 29 | bufferWhenNoUser = false, |
| 30 | }: { |
| 31 | envName: EnvName |
| 32 | bufferWhenNoUser?: boolean |
| 33 | }) { |
| 34 | const buffered: AnalyticsDispatchInput[] = [] |
| 35 | const isDevEnv = envName === 'dev' |
| 36 | |
| 37 | function flushBufferWithUser( |
| 38 | userId: string, |
| 39 | ): AnalyticsDispatchPayload[] { |
| 40 | if (!buffered.length) { |
| 41 | return [] |
| 42 | } |
| 43 | |
| 44 | const toSend: AnalyticsDispatchPayload[] = [] |
| 45 | for (const item of buffered.splice(0)) { |
| 46 | const rebuilt = toTrackableAnalyticsPayload({ |
| 47 | ...item, |
| 48 | fallbackUserId: userId, |
| 49 | }) |
| 50 | if (rebuilt) { |
| 51 | toSend.push(rebuilt) |
| 52 | } |
| 53 | } |
| 54 | return toSend |
| 55 | } |
| 56 | |
| 57 | function process( |
| 58 | input: AnalyticsDispatchInput, |
| 59 | ): AnalyticsDispatchPayload[] { |
| 60 | if (isDevEnv) { |
| 61 | return [] |
| 62 | } |
| 63 | |
| 64 | const payload = toTrackableAnalyticsPayload(input) |
| 65 | if (payload) { |
| 66 | const toSend = flushBufferWithUser(payload.userId) |
| 67 | toSend.push(payload) |
| 68 | return toSend |
| 69 | } |
| 70 | |
| 71 | if ( |
| 72 | bufferWhenNoUser && |
| 73 | getAnalyticsEventId(input.data as AnalyticsLogData) |
| 74 | ) { |
| 75 | buffered.push(input) |
| 76 | } |
| 77 | |
| 78 | return [] |
| 79 | } |
| 80 | |
| 81 | return { process } |
| 82 | } |
no outgoing calls
no test coverage detected