mirror of https://github.com/cupcakearmy/ora.git
69 lines
1.5 KiB
JavaScript
69 lines
1.5 KiB
JavaScript
import dj from 'dayjs'
|
|
import Dexie from 'dexie'
|
|
import RelativeTime from 'dayjs/plugin/relativeTime'
|
|
import Duration from 'dayjs/plugin/duration'
|
|
|
|
import { checkForErrors, DBValidator } from './validation'
|
|
|
|
dj.extend(Duration)
|
|
dj.extend(RelativeTime)
|
|
|
|
export const DB = new Dexie('ora')
|
|
|
|
DB.version(2).stores({
|
|
logs: `++id, host, timestamp`,
|
|
limits: `++id, host`,
|
|
})
|
|
|
|
DB.version(3).stores({
|
|
settings: `key, value`,
|
|
})
|
|
|
|
export function normalizeTimestamp(timestamp) {
|
|
// Normalize every dato to 15 minutes
|
|
const t = dj(timestamp)
|
|
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)
|
|
}
|
|
|
|
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) {
|
|
if (!checkForErrors(DBValidator, data)) throw new Error('Invalid data')
|
|
|
|
await clear()
|
|
await DB.limits.bulkAdd(data.limits)
|
|
await DB.logs.bulkAdd(
|
|
data.logs.map((log) => ({
|
|
...log,
|
|
timestamp: new Date(log.timestamp),
|
|
}))
|
|
)
|
|
}
|
|
|
|
export async function updateOrSet(table, key, value) {
|
|
// const updated = await table.update(key, value)
|
|
// if(updated === 0) await table.
|
|
}
|