Skip to content

Commit

Permalink
fix: should diagnostic track only when api key is valid
Browse files Browse the repository at this point in the history
  • Loading branch information
Mercy811 committed Oct 17, 2023
1 parent e8e00dd commit 03be784
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
22 changes: 22 additions & 0 deletions packages/analytics-browser/test/browser-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,28 @@ describe('browser-client', () => {
expect(diagnosticTrack).toHaveBeenCalledWith(1, 0, core.DIAGNOSTIC_MESSAGES.UNEXPECTED_ERROR);
});

test('should diagnostic track when flush and non 200', async () => {
const transportProvider = {
send: jest.fn().mockImplementationOnce(() => {
return Promise.resolve({
status: Status.Failed,
statusCode: 500,
});
}),
};

await client.init(apiKey, {
defaultTracking: false,
}).promise;
const diagnosticTrack = jest.spyOn(client.config.diagnosticProvider, 'track');
client.config.transportProvider = transportProvider;
client.track('event_type', { userId: 'user_0' });
await client.flush().promise;

expect(diagnosticTrack).toHaveBeenCalledTimes(1);
expect(diagnosticTrack).toHaveBeenCalledWith(1, 0, core.DIAGNOSTIC_MESSAGES.UNEXPECTED_ERROR);
});

test.each([
['api_key', undefined, core.DIAGNOSTIC_MESSAGES.INVALID_OR_MISSING_FIELDS],
[undefined, { time: [0] }, core.DIAGNOSTIC_MESSAGES.EVENT_ERROR],
Expand Down
5 changes: 3 additions & 2 deletions packages/analytics-core/src/plugins/destination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,6 @@ export class Destination implements DestinationPlugin {

async send(list: Context[], useRetry = true) {
if (!this.config.apiKey) {
this.config.diagnosticProvider.track(list.length, 400, DIAGNOSTIC_MESSAGES.MISSING_API_KEY);
return this.fulfillRequest(list, 400, MISSING_API_KEY_MESSAGE);
}

Expand Down Expand Up @@ -213,7 +212,9 @@ export class Destination implements DestinationPlugin {

handleInvalidResponse(res: InvalidResponse, list: Context[], useRetry: boolean) {
if (res.body.missingField || res.body.error.startsWith(INVALID_API_KEY)) {
this.config.diagnosticProvider.track(list.length, 400, DIAGNOSTIC_MESSAGES.INVALID_OR_MISSING_FIELDS);
if (!res.body.error.startsWith(INVALID_API_KEY)) {
this.config.diagnosticProvider.track(list.length, 400, DIAGNOSTIC_MESSAGES.INVALID_OR_MISSING_FIELDS);
}
if (useRetry) {
this.fulfillRequest(list, res.statusCode, `${res.status}: ${getResponseBodyString(res)}`);
}
Expand Down

0 comments on commit 03be784

Please sign in to comment.