Skip to content

Commit

Permalink
fix: update context can be awaited before start (#137)
Browse files Browse the repository at this point in the history
  • Loading branch information
kwasniew committed Jan 24, 2023
1 parent c3554dd commit 35f79bd
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
38 changes: 38 additions & 0 deletions src/index.test.ts
Expand Up @@ -815,6 +815,44 @@ test('Should note include context fields with "null" value', async () => {
expect(url.searchParams.get('sessionId')).toBe('0');
});

test('Should update context fields with await', async () => {
fetchMock.mockResponses(
[JSON.stringify(data), { status: 200 }],
[JSON.stringify(data), { status: 304 }]
);
const config: IConfig = {
url: 'http://localhost/test',
clientKey: '12',
appName: 'web',
environment: 'prod',
};
const client = new UnleashClient(config);
await client.updateContext({
userId: '123',
sessionId: '456',
remoteAddress: 'address',
properties: {
property1: 'property1',
property2: 'property2',
},
});

await client.start();

jest.advanceTimersByTime(1001);

const url = new URL(getTypeSafeRequestUrl(fetchMock));

expect(url.searchParams.get('userId')).toEqual('123');
expect(url.searchParams.get('sessionId')).toEqual('456');
expect(url.searchParams.get('remoteAddress')).toEqual('address');
expect(url.searchParams.get('properties[property1]')).toEqual('property1');
expect(url.searchParams.get('properties[property2]')).toEqual('property2');
expect(url.searchParams.get('appName')).toEqual('web');
expect(url.searchParams.get('environment')).toEqual('prod');
});


test('Should update context fields on request', async () => {
fetchMock.mockResponses(
[JSON.stringify(data), { status: 200 }],
Expand Down
4 changes: 3 additions & 1 deletion src/index.ts
Expand Up @@ -108,6 +108,7 @@ export class UnleashClient extends TinyEmitter {
private customHeaders: Record<string, string>;
private readyEventEmitted = false;
private usePOSTrequests = false;
private started = false;

constructor({
storageProvider,
Expand Down Expand Up @@ -247,7 +248,7 @@ export class UnleashClient extends TinyEmitter {

if (this.timerRef) {
await this.fetchToggles();
} else {
} else if(this.started) {
await new Promise<void>((resolve) => {
const listener = () => {
this.fetchToggles().then(() => {
Expand Down Expand Up @@ -294,6 +295,7 @@ export class UnleashClient extends TinyEmitter {
}

public async start(): Promise<void> {
this.started = true;
if (this.timerRef) {
console.error(
'Unleash SDK has already started, if you want to restart the SDK you should call client.stop() before starting again.'
Expand Down

0 comments on commit 35f79bd

Please sign in to comment.