All files / frontend/clickstream userHashStore.ts

100% Statements 20/20
100% Branches 8/8
100% Functions 3/3
100% Lines 20/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64                                          27x 27x         27x 23x 4x   19x               19x 19x 2x   17x 17x 1x   16x 16x 16x             4x 3x 1x 1x   3x    
/*
  Copyright (C) 2025 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import {v4 as uuidv4} from 'uuid';
import {userIdentifiersStoreSeafPlugin} from '@front/clickstream/userIdentityStoreSeaf';
import env from '@front/helpers/env';
import userStore from '@front/store/userStore';
 
const USER_HASH_KEY = 'seaf_user_hash';
const FIFTY_YEARS_IN_MS = 1576800000000;
 
/**
 * Получение идентификатора (хеша) пользователя
 */
export const getUserHash = async(): Promise<string> => {
  if (env.isPlugin()) {
    return await __getUserHashPlugin();
  } else {
    return __getUserHashWeb();
  }
};
 
/**
 * Если мы запущены как web то хеш пользователя храним в localstorage
 */
function __getUserHashWeb(): string {
  let userHash = userStore.getUserData()?.userId;
  if (userHash) {
    return userHash;
  }
  userHash = localStorage.getItem(USER_HASH_KEY);
  if (userHash) {
    return userHash;
  }
  userHash = uuidv4();
  localStorage.setItem(USER_HASH_KEY, userHash);
  return userHash;
}
 
/**
 * Если мы запущены как plugin то хеш пользователя храним в хранилище плагина
 */
async function __getUserHashPlugin(): Promise<string> {
  let userHash = await userIdentifiersStoreSeafPlugin.getData(USER_HASH_KEY);
  if (!userHash) {
    userHash = uuidv4();
    await userIdentifiersStoreSeafPlugin.setData(USER_HASH_KEY, userHash, FIFTY_YEARS_IN_MS);
  }
  return userHash;
}