ora/src/shared/db.js

42 lines
998 B
JavaScript
Raw Normal View History

2020-09-20 22:24:57 +02:00
import dj from 'dayjs'
import RelativeTime from 'dayjs/plugin/relativeTime'
import Duration from 'dayjs/plugin/duration'
2021-11-23 01:45:19 +01:00
import Dexie from 'dexie'
import 'dexie-export-import'
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() {
2021-11-23 01:45:19 +01:00
return Promise.allSettled(DB.tables.map((table) => DB.table(table.name).clear()))
2021-11-22 20:07:06 +01:00
}