All files / modules/85-cv/hooks/IndexedDBHook IndexedDBHook.ts

91.11% Statements 41/45
66.67% Branches 24/36
90.91% Functions 10/11
91.11% Lines 41/45

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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173              29x 29x 29x 29x 29x 29x   29x                 29x                 29x                 29x   29x                                                                                                                 7x 7x   7x 42x 42x 36x 30x 30x     6x                 1x 1x     4x                             29x 16x 16x 16x 16x 7x 4x 4x 4x         16x 5x 5x           16x 7x 5x 5x 5x           16x    
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import { openDB, IDBPDatabase } from 'idb'
import { useEffect, useState } from 'react'
import SessionToken from 'framework/utils/SessionToken'
import { useToaster } from '@common/exports'
import { ModuleName } from 'framework/types/ModuleName'
import { loggerFor } from 'framework/logging/logging'
 
export const CVObjectStoreNames = {
  LIST_ENTITIES: 'datasourceListEntity',
  APPD_TIERS: 'appDTiers',
  ONBOARDING_JOURNEY: 'onBoardingJourney', // Remove this when old onboarding is removed
  SETUP: 'setup', // New setup/onboading journey
  ONBOARDING_SOURCES: 'onBoardingSources',
  MONITORED_SERVICE: 'monitoredService'
}
 
export const CVIndexedDBPrimaryKeys = {
  APPD_APP_NAME: 'applicationName',
  APPD_APP_ID: 'appId',
  DATASOURCE_ID: 'dataSourceId',
  SETUP_ID: 'setupID',
  SOURCE_ID: 'sourceID',
  MONITORED_SERVICE: 'monitoredService'
}
 
export const CVIndexedObjectStoreToPrimaryKey = {
  [CVObjectStoreNames.LIST_ENTITIES]: CVIndexedDBPrimaryKeys.DATASOURCE_ID,
  [CVObjectStoreNames.APPD_TIERS]: [CVIndexedDBPrimaryKeys.APPD_APP_ID, CVIndexedDBPrimaryKeys.DATASOURCE_ID],
  [CVObjectStoreNames.ONBOARDING_JOURNEY]: CVIndexedDBPrimaryKeys.DATASOURCE_ID,
  [CVObjectStoreNames.SETUP]: CVIndexedDBPrimaryKeys.SETUP_ID,
  [CVObjectStoreNames.ONBOARDING_SOURCES]: CVIndexedDBPrimaryKeys.SOURCE_ID,
  [CVObjectStoreNames.MONITORED_SERVICE]: CVIndexedDBPrimaryKeys.MONITORED_SERVICE
}
 
const logger = loggerFor(ModuleName.CV)
 
const OBJECT_STORES = [
  {
    name: CVObjectStoreNames.LIST_ENTITIES,
    options: { keyPath: CVIndexedObjectStoreToPrimaryKey[CVObjectStoreNames.LIST_ENTITIES], autoIncrement: false }
  },
  {
    name: CVObjectStoreNames.APPD_TIERS,
    options: {
      keyPath: CVIndexedObjectStoreToPrimaryKey[CVObjectStoreNames.APPD_TIERS],
      autoIncrement: false
    },
    index: {
      indexName: 'appDTiersIndex',
      property: CVIndexedObjectStoreToPrimaryKey[CVObjectStoreNames.APPD_TIERS],
      options: { multiEntry: false, unique: true }
    }
  },
  {
    name: CVObjectStoreNames.ONBOARDING_JOURNEY,
    options: { keyPath: CVIndexedDBPrimaryKeys.DATASOURCE_ID, autoIncrement: false },
    index: {
      indexName: 'onBoardingJourneyIndex',
      property: CVIndexedObjectStoreToPrimaryKey[CVObjectStoreNames.ONBOARDING_JOURNEY],
      options: { unique: true }
    }
  },
  {
    name: CVObjectStoreNames.SETUP,
    options: { keyPath: CVIndexedDBPrimaryKeys.SETUP_ID, autoIncrement: false },
    index: {
      indexName: 'setUpJourneyIndex',
      property: CVIndexedObjectStoreToPrimaryKey[CVObjectStoreNames.SETUP],
      options: { unique: true }
    }
  },
 
  {
    name: CVObjectStoreNames.ONBOARDING_SOURCES,
    options: { keyPath: CVIndexedDBPrimaryKeys.SOURCE_ID, autoIncrement: false },
    index: {
      indexName: 'onBoardingSourcesIndex',
      property: CVIndexedObjectStoreToPrimaryKey[CVObjectStoreNames.ONBOARDING_SOURCES],
      options: { unique: true }
    }
  },
  {
    name: CVObjectStoreNames.MONITORED_SERVICE,
    options: { keyPath: CVIndexedDBPrimaryKeys.MONITORED_SERVICE, autoIncrement: false },
    index: {
      indexName: 'monitoredServiceIndex',
      property: CVIndexedObjectStoreToPrimaryKey[CVObjectStoreNames.MONITORED_SERVICE],
      options: { unique: true }
    }
  }
]
 
async function initializeCVDB(setDBInstance: (dbInstance?: IDBPDatabase) => void): Promise<IDBPDatabase | void> {
  try {
    const dbInstance = await openDB('CV-INDEXED-DB', SessionToken.getLastTokenSetTime() || new Date().getTime(), {
      upgrade(db) {
        for (const store of OBJECT_STORES) {
          try {
            const dbStore = db.createObjectStore(store.name, store.options)
            if (store.index) {
              const { indexName, property, options } = store.index
              dbStore.createIndex(indexName, property, options)
            }
          } catch (exception) {
            logger.error(`Exception thrown when attempting to create an object store: ${exception}`)
          }
        }
      },
      blocked() {
        dbInstance?.close()
        setDBInstance()
      },
      blocking() {
        dbInstance?.close()
        setDBInstance()
      }
    })
    return dbInstance
  } catch (e) {
    logger.error(`Exception thrown by indexedDB: ${e}`)
  }
}
 
type CVIndexedDBHookReturnType = {
  isInitializingDB: boolean
  dbInstance?: IDBPDatabase
}
 
interface CVIndexDBHookProps {
  clearStroreList?: string[] // making it optional for now, change it after removing usages in old onboarding
}
 
export function useIndexedDBHook(props?: CVIndexDBHookProps): CVIndexedDBHookReturnType {
  const [isInitializingDB, setInitializingDB] = useState<boolean>(true)
  const [dbInstance, setDBInstance] = useState<IDBPDatabase | undefined>()
  const { showWarning } = useToaster()
  useEffect(() => {
    initializeCVDB(setDBInstance).then(db => {
      Eif (db) {
        setDBInstance(db)
        setInitializingDB(false)
      }
    })
  }, [])
 
  const clearDB = async (item: string) => {
    try {
      await dbInstance?.clear(item)
    } catch (e) {
      showWarning(e)
    }
  }
 
  useEffect(() => {
    return () => {
      Eif (props?.clearStroreList?.length) {
        props?.clearStroreList?.map(item => {
          clearDB(item)
        })
      }
    }
  }, [dbInstance])
 
  return { isInitializingDB, dbInstance }
}