All files / app/codeCharta/util/indexedDB indexedDBWriter.ts

100% Statements 23/23
100% Branches 7/7
100% Functions 5/5
100% Lines 23/23

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  7x   7x 7x 7x 7x 7x   7x 1x 1x 1x       1x     7x 3x 3x 3x     7x 1x 1x 1x 1x       5x   1x 1x          
import { CcState } from "app/codeCharta/codeCharta.model"
import { openDB } from "idb"
 
export const DB_NAME = "CodeCharta"
export const DB_VERSION = 1
export const CCSTATE_STORE_NAME = "ccstate"
export const CCSTATE_PRIMARY_KEY = "id"
export const CCSTATE_STATE_ID = 1001
 
export async function writeCcState(state: CcState) {
    const database = await createOrOpenCcStateStore()
    const tx = database.transaction(CCSTATE_STORE_NAME, "readwrite")
    await tx.store.put({
        [CCSTATE_PRIMARY_KEY]: CCSTATE_STATE_ID,
        state
    })
    await tx.done
}
 
export async function readCcState(): Promise<CcState | null> {
    const database = await createOrOpenCcStateStore()
    const record = await database.get(CCSTATE_STORE_NAME, CCSTATE_STATE_ID)
    return record?.state || null
}
 
export async function deleteCcState() {
    const database = await createOrOpenCcStateStore()
    const tx = database.transaction(CCSTATE_STORE_NAME, "readwrite")
    await tx.store.delete(CCSTATE_STATE_ID)
    await tx.done
}
 
async function createOrOpenCcStateStore() {
    return openDB(DB_NAME, DB_VERSION, {
        upgrade(database) {
            if (!database.objectStoreNames.contains(CCSTATE_STORE_NAME)) {
                database.createObjectStore(CCSTATE_STORE_NAME, { keyPath: CCSTATE_PRIMARY_KEY })
            }
        }
    })
}