Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions sdk/analytics.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { pino, Logger } from 'pino';
import { Fetch } from './types.js';
import { FlagsmithConfig } from './types.js';
import { Dispatcher } from 'undici-types';
import { Fetch, FlagsmithConfig } from './types.js';
import { getUserAgent } from './utils.js';

export const ANALYTICS_ENDPOINT = './analytics/flags/';
Expand All @@ -22,6 +22,10 @@ export interface AnalyticsProcessorOptions {
logger?: Logger;
/** Custom {@link fetch} implementation to use for API requests. **/
fetch?: Fetch;
/** A custom {@link Dispatcher} to use for API requests. **/
agent?: Dispatcher;
/** Custom headers to send with API requests. **/
customHeaders?: FlagsmithConfig['customHeaders'];

/** @deprecated Use {@link analyticsUrl} instead. **/
baseApiUrl?: string;
Expand All @@ -45,6 +49,8 @@ export class AnalyticsProcessor {
private logger: Logger;
private currentFlush: ReturnType<typeof fetch> | undefined;
private customFetch: Fetch;
private agent?: Dispatcher;
private customHeaders?: FlagsmithConfig['customHeaders'];

constructor(data: AnalyticsProcessorOptions) {
this.analyticsUrl = data.analyticsUrl || data.baseApiUrl + ANALYTICS_ENDPOINT;
Expand All @@ -54,6 +60,8 @@ export class AnalyticsProcessor {
this.requestTimeoutMs = data.requestTimeoutMs || this.requestTimeoutMs;
this.logger = data.logger || pino();
this.customFetch = data.fetch ?? fetch;
this.agent = data.agent;
this.customHeaders = data.customHeaders;
}
/**
* Try to flush pending collected data to the Flagsmith analytics API.
Expand All @@ -64,16 +72,25 @@ export class AnalyticsProcessor {
}

try {
this.currentFlush = this.customFetch(this.analyticsUrl, {
const customHeaders = new Headers(this.customHeaders);
customHeaders.delete('Content-Type');
customHeaders.delete('X-Environment-Key');
customHeaders.delete('User-Agent');

// built-in RequestInit type doesn't have dispatcher/agent
const init: RequestInit & { dispatcher?: Dispatcher } = {
dispatcher: this.agent,
method: 'POST',
body: JSON.stringify(this.analyticsData),
signal: AbortSignal.timeout(this.requestTimeoutMs),
headers: {
...Object.fromEntries(customHeaders),
'Content-Type': 'application/json',
'X-Environment-Key': this.environmentKey,
'User-Agent': getUserAgent()
}
});
};
this.currentFlush = this.customFetch(this.analyticsUrl, init);
await this.currentFlush;
} catch (error) {
// We don't want failing to write analytics to cause any exceptions in the main
Expand Down
5 changes: 4 additions & 1 deletion sdk/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,10 @@ export class Flagsmith {
environmentKey: this.environmentKey,
analyticsUrl: this.analyticsUrl,
requestTimeoutMs: this.requestTimeoutMs,
logger: this.logger
logger: this.logger,
fetch: this.customFetch,
agent: this.agent,
customHeaders: this.customHeaders
});
}

Expand Down
37 changes: 36 additions & 1 deletion tests/sdk/analytics.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getUserAgent } from '../../sdk/utils.js';
import { fetch } from './fetchMock.js';
import { analyticsProcessor } from './utils.js';
import { analyticsProcessor, apiKey, flagsmith } from './utils.js';
import { Dispatcher } from 'undici-types';

test('test_analytics_processor_track_feature_updates_analytics_data', () => {
const aP = analyticsProcessor();
Expand Down Expand Up @@ -38,6 +39,40 @@ test('test_analytics_processor_flush_post_request_data_match_ananlytics_data', a
);
});

const customHeaders = {
'X-Custom-Header': 'value',
'x-environment-key': 'wrong-key',
'content-type': 'text/plain',
'user-agent': 'wrong-agent'
};

test.each<{ format: string; headers: HeadersInit }>([
{ format: 'record', headers: customHeaders },
{ format: 'Headers', headers: new Headers(customHeaders) },
{ format: 'tuples', headers: Object.entries(customHeaders) }
])('analytics uses the client transport and $format headers', async ({ headers }) => {
const agent = {} as Dispatcher;
const customFetch = vi.fn((url, options) => fetch(url.toString(), options));
const client = flagsmith({
enableAnalytics: true,
fetch: customFetch,
agent,
customHeaders: headers
});
const flags = await client.getEnvironmentFlags();
flags.getFlag('some_feature');

await client['analyticsProcessor']!.flush();

const request = customFetch.mock.calls.find(([url]) => url.includes('analytics/flags/'))?.[1];
expect(request?.dispatcher).toBe(agent);
const postedHeaders = new Headers(request?.headers);
expect(postedHeaders.get('x-custom-header')).toBe('value');
expect(postedHeaders.get('x-environment-key')).toBe(apiKey());
expect(postedHeaders.get('content-type')).toBe('application/json');
expect(postedHeaders.get('user-agent')).toBe(getUserAgent());
});

vi.useFakeTimers();
test('test_analytics_processor_flush_post_request_data_match_ananlytics_data_test', async () => {
const aP = analyticsProcessor();
Expand Down