From 6c7c3bacebe3f8c6077f5d2532d5a06259e374bf Mon Sep 17 00:00:00 2001 From: Tim Yiu <137842098+tyiuhc@users.noreply.github.com> Date: Fri, 10 Jan 2025 14:35:25 -0800 Subject: [PATCH] feat: migrate to use web_exp_id for web experiment device_id bucketing (#154) --- packages/experiment-tag/src/experiment.ts | 35 +++++++++---------- .../experiment-tag/test/experiment.test.ts | 3 +- 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/packages/experiment-tag/src/experiment.ts b/packages/experiment-tag/src/experiment.ts index dcc3e37..6a1bcfe 100644 --- a/packages/experiment-tag/src/experiment.ts +++ b/packages/experiment-tag/src/experiment.ts @@ -59,24 +59,23 @@ export const initializeExperiment = async ( user = {}; } - // create new user if it does not exist, or it does not have device_id or web_exp_id - if (Object.keys(user).length === 0 || !user.device_id || !user.web_exp_id) { - if (!user.device_id || !user.web_exp_id) { - // if user has device_id, migrate it to web_exp_id - if (user.device_id) { - user.web_exp_id = user.device_id; - } else if (user.web_exp_id) { - user.device_id = user.web_exp_id; - } else { - const uuid = UUID(); - // both IDs are set for backwards compatibility, to be removed in future update - user = { device_id: uuid, web_exp_id: uuid }; - } - globalScope.localStorage.setItem( - experimentStorageName, - JSON.stringify(user), - ); - } + // if web_exp_id does not exist: + // 1. if device_id exists, migrate device_id to web_exp_id and remove device_id + // 2. if device_id does not exist, create a new web_exp_id + // 3. if both device_id and web_exp_id exist, remove device_id + if (!user.web_exp_id) { + user.web_exp_id = user.device_id || UUID(); + delete user.device_id; + globalScope.localStorage.setItem( + experimentStorageName, + JSON.stringify(user), + ); + } else if (user.web_exp_id && user.device_id) { + delete user.device_id; + globalScope.localStorage.setItem( + experimentStorageName, + JSON.stringify(user), + ); } const urlParams = getUrlParams(); diff --git a/packages/experiment-tag/test/experiment.test.ts b/packages/experiment-tag/test/experiment.test.ts index 4838e52..71fec36 100644 --- a/packages/experiment-tag/test/experiment.test.ts +++ b/packages/experiment-tag/test/experiment.test.ts @@ -55,12 +55,11 @@ describe('initializeExperiment', () => { test('should initialize experiment with empty user', () => { initializeExperiment(stringify(apiKey), JSON.stringify([])); expect(ExperimentClient.prototype.setUser).toHaveBeenCalledWith({ - device_id: 'mock', web_exp_id: 'mock', }); expect(mockGlobal.localStorage.setItem).toHaveBeenCalledWith( 'EXP_1', - JSON.stringify({ device_id: 'mock', web_exp_id: 'mock' }), + JSON.stringify({ web_exp_id: 'mock' }), ); });