electron/lib/renderer/extensions/storage.ts

87 lines
2.7 KiB
TypeScript
Raw Normal View History

import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal'
const getStorage = (storageType: string, extensionId: number, callback: Function) => {
if (typeof callback !== 'function') throw new TypeError('No callback provided')
ipcRendererInternal.invoke<string>('CHROME_STORAGE_READ', storageType, extensionId)
.then(data => {
if (data !== null) {
callback(JSON.parse(data))
} else {
// Disabled due to false positive in StandardJS
// eslint-disable-next-line standard/no-callback-literal
callback({})
}
})
2016-06-09 21:14:14 +00:00
}
const setStorage = (storageType: string, extensionId: number, storage: Record<string, any>, callback: Function) => {
2017-07-10 22:35:53 +00:00
const json = JSON.stringify(storage)
ipcRendererInternal.invoke('CHROME_STORAGE_WRITE', storageType, extensionId, json)
.then(() => {
if (callback) callback()
})
2016-06-28 20:02:03 +00:00
}
const getStorageManager = (storageType: string, extensionId: number) => {
2016-06-28 09:02:25 +00:00
return {
get (keys: string[], callback: Function) {
getStorage(storageType, extensionId, (storage: Record<string, any>) => {
2017-07-10 22:35:53 +00:00
if (keys == null) return callback(storage)
let defaults: Record<string, any> = {}
2017-07-10 22:35:53 +00:00
switch (typeof keys) {
case 'string':
keys = [keys]
break
case 'object':
if (!Array.isArray(keys)) {
defaults = keys
keys = Object.keys(keys)
}
break
}
// Disabled due to false positive in StandardJS
// eslint-disable-next-line standard/no-callback-literal
2017-07-10 22:35:53 +00:00
if (keys.length === 0) return callback({})
const items: Record<string, any> = {}
keys.forEach((key: string) => {
let value = storage[key]
2017-07-10 22:35:53 +00:00
if (value == null) value = defaults[key]
items[key] = value
})
callback(items)
2016-06-09 21:14:14 +00:00
})
},
set (items: Record<string, any>, callback: Function) {
getStorage(storageType, extensionId, (storage: Record<string, any>) => {
Object.keys(items).forEach(name => { storage[name] = items[name] })
2017-07-10 22:35:53 +00:00
setStorage(storageType, extensionId, storage, callback)
2016-06-09 21:14:14 +00:00
})
},
remove (keys: string[], callback: Function) {
getStorage(storageType, extensionId, (storage: Record<string, any>) => {
if (!Array.isArray(keys)) keys = [keys]
keys.forEach((key: string) => {
2017-07-10 22:35:53 +00:00
delete storage[key]
})
2017-07-10 22:35:53 +00:00
setStorage(storageType, extensionId, storage, callback)
})
},
clear (callback: Function) {
2017-07-10 22:35:53 +00:00
setStorage(storageType, extensionId, {}, callback)
2016-06-09 21:14:14 +00:00
}
}
}
2016-06-28 09:02:25 +00:00
export const setup = (extensionId: number) => ({
sync: getStorageManager('sync', extensionId),
local: getStorageManager('local', extensionId)
})