ora/src/shared/db.js

69 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-09-20 22:24:57 +02:00
import dj from 'dayjs'
import Dexie from 'dexie'
2020-09-20 22:24:57 +02:00
import RelativeTime from 'dayjs/plugin/relativeTime'
import Duration from 'dayjs/plugin/duration'
2021-11-22 20:07:06 +01:00
import { checkForErrors, DBValidator } from './validation'
2020-09-20 22:24:57 +02:00
dj.extend(Duration)
dj.extend(RelativeTime)
2020-09-18 21:00:59 +02:00
export const DB = new Dexie('ora')
2021-11-22 20:07:06 +01:00
DB.version(2).stores({
logs: `++id, host, timestamp`,
limits: `++id, host`,
2020-09-18 21:00:59 +02:00
})
2020-09-19 01:16:43 +02:00
2021-11-22 20:07:06 +01:00
DB.version(3).stores({
settings: `key, value`,
})
2020-09-19 01:16:43 +02:00
export function normalizeTimestamp(timestamp) {
// Normalize every dato to 15 minutes
2020-09-20 22:24:57 +02:00
const t = dj(timestamp)
2020-09-19 01:16:43 +02:00
const min = t.minute()
return t
.millisecond(0)
.second(0)
.minute(min - (min % 15))
.toDate()
}
export async function insertLog({ timestamp, host, seconds }) {
const saved = await DB.logs.where({ host, timestamp }).first()
const data = Object.assign({ host, timestamp, seconds: 0 }, saved)
data.seconds += seconds
await DB.logs.put(data)
2020-09-19 01:16:43 +02:00
}
2020-10-11 23:46:06 +02:00
export async function clear() {
await DB.limits.clear()
await DB.logs.clear()
}
export async function dump() {
return {
limits: await DB.limits.toArray(),
logs: await DB.logs.toArray(),
}
}
export async function load(data) {
2021-11-22 20:07:06 +01:00
if (!checkForErrors(DBValidator, data)) throw new Error('Invalid data')
2020-10-11 23:46:06 +02:00
await clear()
await DB.limits.bulkAdd(data.limits)
await DB.logs.bulkAdd(
data.logs.map((log) => ({
...log,
timestamp: new Date(log.timestamp),
}))
)
}
2021-11-22 20:07:06 +01:00
export async function updateOrSet(table, key, value) {
// const updated = await table.update(key, value)
// if(updated === 0) await table.
}