import dj from 'dayjs' import RelativeTime from 'dayjs/plugin/relativeTime' import Duration from 'dayjs/plugin/duration' import Dexie from 'dexie' import 'dexie-export-import' import { LogValidator, checkForErrors } from '../shared/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`, dismiss: `host, timestamp, duration`, }) 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 const error = checkForErrors(LogValidator, data) if (error) throw new Error(error) await DB.logs.put(data) } export async function clear() { return Promise.allSettled(DB.tables.map((table) => DB.table(table.name).clear())) }