pinafore/routes/_database/helpers.js

52 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-02-09 06:04:10 +00:00
import { dbPromise, getDatabase } from './databaseLifecycle'
import { getInCache, hasInCache, setInCache } from './cache'
2018-02-14 03:34:37 +00:00
import { ACCOUNT_ID, REBLOG_ID, STATUS_ID, TIMESTAMP } from './constants'
2018-02-09 06:04:10 +00:00
2018-02-09 06:29:29 +00:00
export async function getGenericEntityWithId (store, cache, instanceName, id) {
2018-02-09 06:04:10 +00:00
if (hasInCache(cache, instanceName, id)) {
return getInCache(cache, instanceName, id)
}
const db = await getDatabase(instanceName)
let result = await dbPromise(db, store, 'readonly', (store, callback) => {
store.get(id).onsuccess = (e) => callback(e.target.result)
})
setInCache(cache, instanceName, id, result)
return result
}
2018-02-09 06:29:29 +00:00
export async function setGenericEntityWithId (store, cache, instanceName, entity) {
2018-02-09 06:04:10 +00:00
setInCache(cache, instanceName, entity.id, entity)
const db = await getDatabase(instanceName)
2018-02-09 06:29:29 +00:00
return dbPromise(db, store, 'readwrite', (store) => {
2018-02-09 06:04:10 +00:00
store.put(entity)
})
2018-02-09 06:29:29 +00:00
}
2018-02-14 03:34:37 +00:00
export function cloneForStorage (obj) {
let res = {}
let keys = Object.keys(obj)
for (let key of keys) {
let value = obj[key]
// save storage space by skipping nulls, 0s, falses, empty strings, and empty arrays
if (!value || (Array.isArray(value) && value.length === 0)) {
continue
}
switch (key) {
case 'account':
res[ACCOUNT_ID] = value.id
break
case 'status':
res[STATUS_ID] = value.id
break
case 'reblog':
res[REBLOG_ID] = value.id
break
default:
res[key] = value
break
}
}
res[TIMESTAMP] = Date.now()
return res
2018-02-14 03:35:46 +00:00
}