All files / rusted-chromium/store readStore.ts

100% Statements 22/22
100% Branches 7/7
100% Functions 1/1
100% Lines 22/22

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 373x   3x   3x 3x 3x           3x 7x 7x 1x 1x 1x     6x 6x 3x 1x 1x   5x 2x 3x 2x   1x   5x      
import { readFile } from 'node:fs/promises'
 
import { READ_CONFIG } from '../commons/loggerTexts'
import type { IStoreConfig } from '../interfaces/interfaces'
import { spinner } from '../log/spinner'
import { existsAndIsFile } from '../utils/file.utils'
import { Store } from './Store'
 
/**
 * Reads a store file from a given path on the local file system
 * @param config 
 */
export async function readStoreFile(config: IStoreConfig): Promise<Store> {
    spinner.start(READ_CONFIG)
    if (!(await existsAndIsFile(config.url))) {
        const reason = 'File does not exist'
        spinner.error(reason)
        throw new Error(reason)
    }
 
    try {
        const store = await readFile(config.url, { encoding: 'utf-8' })
        const parsedStore = JSON.parse(store)
        spinner.success()
        return new Store(parsedStore)
    } catch (e) {
        if (e instanceof SyntaxError) {
            spinner.error('Unable to parse JSON file')
        } else if (e && typeof e === 'object') {
            spinner.error(e.toString())
        } else {
            spinner.error(e as string)
        }
        throw e
    }
}