Skip to content

Commit

Permalink
Tagging API calls
Browse files Browse the repository at this point in the history
  • Loading branch information
aklarfeld committed Apr 9, 2024
1 parent f1f67e6 commit a1212d5
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 7 deletions.
23 changes: 18 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ import {
getEndpointConfigForRequest
} from './utils';
import { postEvents, fetchRemoteConfig, postTelemetry } from './api';
import v8 from 'v8';
import {
HeaderOptionType,
EventRequestType,
ConfigType,
LoggerType,
RequestType,
MetadataType
MetadataType,
SupergoodContext
} from './types';
import {
defaultConfig,
Expand All @@ -32,6 +32,9 @@ import { IsomorphicRequest } from './interceptor/utils/IsomorphicRequest';
import { IsomorphicResponse } from './interceptor/utils/IsomorphicResponse';
import { BatchInterceptor } from './interceptor/BatchInterceptor';
import { FetchInterceptor } from './interceptor/FetchInterceptor';
import { AsyncLocalStorage } from "async_hooks";

const supergoodAsyncLocalStorage = new AsyncLocalStorage<SupergoodContext>();

const Supergood = () => {
let eventSinkUrl: string;
Expand Down Expand Up @@ -293,7 +296,7 @@ const Supergood = () => {
const responseArray = prepareData(
responseCacheValues as EventRequestType[],
supergoodConfig.remoteConfig,
supergoodTags,
{ ...supergoodTags, ...(supergoodAsyncLocalStorage.getStore()?.tags || {}) }
) as Array<EventRequestType>;

let data = [...responseArray];
Expand All @@ -303,7 +306,7 @@ const Supergood = () => {
const requestArray = prepareData(
requestCacheValues as EventRequestType[],
supergoodConfig.remoteConfig,
supergoodTags
{ ...supergoodTags, ...(supergoodAsyncLocalStorage.getStore()?.tags || {}) }
) as Array<EventRequestType>;
data = [...requestArray, ...responseArray];
}
Expand Down Expand Up @@ -396,16 +399,26 @@ const Supergood = () => {
};

const waitAndFlushCache = async ({ force } = { force: false }) => {
// If the request cache isn't empty, this means that
// there are responses that are still being processed.
// Wait for them to finish before flushing the cache.
if (requestCache.keys().length > 0) {
await sleep(supergoodConfig.waitAfterClose);
}

await flushCache({ force });
}

const withContext = async <TRet>(
tags: Record<string, string | number | string[]>,
fn: () => Promise<TRet>,
): Promise<TRet> => {
return supergoodAsyncLocalStorage.run({ tags }, fn);
}

// Set up cleanup catch for exit signals
onExit(() => close(), { alwaysLast: true });
return { close, flushCache, waitAndFlushCache, init };
return { close, flushCache, waitAndFlushCache, withContext, init };
};

export = Supergood();
7 changes: 6 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ interface EventRequestType {
};
}

type SupergoodContext = {
tags: Record<string, string | number | string[]>;
};

// interface EventResponseType {}

type ErrorPayloadType = {
Expand Down Expand Up @@ -168,5 +172,6 @@ export type {
EndpointConfigType,
RemoteConfigPayloadType,
MetadataType,
TelemetryType
TelemetryType,
SupergoodContext
};
23 changes: 22 additions & 1 deletion test/e2e/tags.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { getEvents } from '../utils/function-call-args';
import { mockApi } from '../utils/mock-api';

describe('Custom tags', () => {
it('should add custom tags to events', async () => {
it('should add custom tags to events via init', async () => {
// Add your test code here
const { postEventsMock } = mockApi();
await Supergood.init(
Expand All @@ -34,4 +34,25 @@ describe('Custom tags', () => {
expect(eventsPosted.length).toEqual(1);
expect(get(eventsPosted[0], 'metadata.tags.customTag')).toEqual('customValue');
});

it('should add custom tags to events via asyncLocalStorage', async () => {
const { postEventsMock } = mockApi();
await Supergood.init(
{
config: { ...SUPERGOOD_CONFIG, allowLocalUrls: true },
clientId: SUPERGOOD_CLIENT_ID,
clientSecret: SUPERGOOD_CLIENT_SECRET,
},
SUPERGOOD_SERVER
);

await Supergood.withContext({ customTag: 'customValue' }, async () => {
await fetch(`${MOCK_DATA_SERVER}/profile`);
await Supergood.waitAndFlushCache();
});

const eventsPosted = getEvents(postEventsMock);
expect(eventsPosted.length).toEqual(1);
expect(get(eventsPosted[0], 'metadata.tags.customTag')).toEqual('customValue');
});
})

0 comments on commit a1212d5

Please sign in to comment.