Skip to content

Commit

Permalink
also probably not going to change
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaellehmkuhl committed Nov 7, 2024
1 parent a9141bb commit 53fa3e4
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/libs/electron/filesystemStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { app } from 'electron'
import fs from 'fs/promises'
import { dirname, join } from 'path'

import { StorageDB } from '@/types/general'

import { isElectron } from '../utils'

// Create a new storage interface for filesystem
const cockpitFolderPath = join(app.getPath('userData'), 'Cockpit')
const filesystemOnlyInElectronErrorMsg = 'Filesystem storage is only available in Electron.'

export const filesystemStorage: StorageDB = {
async setItem(key: string, value: Blob): Promise<Blob> {
if (!isElectron()) throw new Error(filesystemOnlyInElectronErrorMsg)
console.log('setItem on electron', key)
const filePath = join(cockpitFolderPath, key)
await fs.mkdir(dirname(filePath), { recursive: true })
await fs.writeFile(filePath, Buffer.from(await value.arrayBuffer()))
return value
},
async getItem(key: string): Promise<Blob | null> {
if (!isElectron()) throw new Error(filesystemOnlyInElectronErrorMsg)
console.log('getItem on electron', key)
const filePath = join(cockpitFolderPath, key)
try {
const buffer = await fs.readFile(filePath)
return new Blob([buffer])
} catch (error) {
if (error.code === 'ENOENT') return null
throw error
}
},
async removeItem(key: string): Promise<void> {
if (!isElectron()) throw new Error(filesystemOnlyInElectronErrorMsg)
const filePath = join(cockpitFolderPath, key)
await fs.unlink(filePath)
},
async clear(): Promise<void> {
if (!isElectron()) throw new Error(filesystemOnlyInElectronErrorMsg)
throw new Error(
`Clear functionality is not available in the filesystem storage, so we don't risk losing important data. If you
want to clear the storage, please delete the Cockpit folder in your user data directory manually.`
)
},
async keys(): Promise<string[]> {
if (!isElectron()) throw new Error(filesystemOnlyInElectronErrorMsg)
const dirPath = cockpitFolderPath
try {
return await fs.readdir(dirPath)
} catch (error) {
if (error.code === 'ENOENT') return []
throw error
}
},
async iterate(callback: (value: unknown, key: string, iterationNumber: number) => void): Promise<void> {
if (!isElectron()) throw new Error(filesystemOnlyInElectronErrorMsg)
const keys = await this.keys()
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const value = await this.getItem(key)
callback(value, key, i)
}
},
}

0 comments on commit 53fa3e4

Please sign in to comment.