Pinafore-Web-Client-Frontend/src/routes/_database/helpers.js

58 lines
1.7 KiB
JavaScript
Raw Normal View History

import { dbPromise, getDatabase } from './databaseLifecycle.js'
import { getInCache, hasInCache, setInCache } from './cache.js'
import {
ACCOUNT_ID, REBLOG_ID, STATUS_ID, TIMESTAMP, USERNAME_LOWERCASE, CURRENT_TIME
} from './constants.js'
2018-02-09 07:04:10 +01:00
2018-02-09 07:29:29 +01:00
export async function getGenericEntityWithId (store, cache, instanceName, id) {
2018-02-09 07:04:10 +01:00
if (hasInCache(cache, instanceName, id)) {
return getInCache(cache, instanceName, id)
}
const db = await getDatabase(instanceName)
2019-08-03 22:49:37 +02:00
const result = await dbPromise(db, store, 'readonly', (store, callback) => {
2018-02-09 07:04:10 +01:00
store.get(id).onsuccess = (e) => callback(e.target.result)
})
setInCache(cache, instanceName, id, result)
return result
}
2018-02-09 07:29:29 +01:00
export async function setGenericEntityWithId (store, cache, instanceName, entity) {
2018-02-09 07:04:10 +01:00
setInCache(cache, instanceName, entity.id, entity)
const db = await getDatabase(instanceName)
2018-02-09 07:29:29 +01:00
return dbPromise(db, store, 'readwrite', (store) => {
2018-02-09 07:04:10 +01:00
store.put(entity)
})
2018-02-09 07:29:29 +01:00
}
2018-02-14 04:34:37 +01:00
export function cloneForStorage (obj) {
2019-08-03 22:49:37 +02:00
const res = {}
const keys = Object.keys(obj)
for (const key of keys) {
const value = obj[key]
2018-02-14 04:34:37 +01:00
// 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
2018-03-25 03:04:54 +02:00
case 'acct':
res[key] = value
res[USERNAME_LOWERCASE] = value.toLowerCase()
break
2018-02-14 04:34:37 +01:00
default:
res[key] = value
break
}
}
res[TIMESTAMP] = CURRENT_TIME.now()
2018-02-14 04:34:37 +01:00
return res
2018-02-14 04:35:46 +01:00
}