/
MockServerTelemetryExporter.ts
45 lines (40 loc) · 1.65 KB
/
MockServerTelemetryExporter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import type { TelemetryEventInput, TelemetryExporter } from '@sourcegraph/telemetry'
import { logError } from '../../logger'
import { isError } from '../../utils'
const MOCK_URL = `http://localhost:4930${process.env.VITEST_POOL_ID || '0'}`
const ENDPOINT = '/.api/mockEventRecording'
/**
* MockServerTelemetryExporter exports events to a mock endpoint at
* http://localhost:4930${/.api/mockEventRecording
*/
export class MockServerTelemetryExporter implements TelemetryExporter {
constructor(private anonymousUserID: string) {}
public async exportEvents(events: TelemetryEventInput[]): Promise<void> {
const resultOrError = await this.postTestEventRecording(events)
if (isError(resultOrError)) {
logError('MockServerTelemetryExporter', 'Error exporting telemetry events:', resultOrError)
}
}
private postTestEventRecording<T>(events: TelemetryEventInput[]): Promise<T | Error> {
const headers = new Headers({
'Content-Type': 'application/json',
'X-Sourcegraph-Actor-Anonymous-UID': this.anonymousUserID,
})
return fetch(`${MOCK_URL}${ENDPOINT}`, {
method: 'POST',
headers,
body: JSON.stringify(events),
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP status code: ${response.status}`)
}
return response
})
.then(response => response.json() as T)
.catch(
error =>
new Error(`error sending data to mock event-recording API: ${error} (${MOCK_URL})`)
)
}
}