33 lines
1.9 KiB
JavaScript
33 lines
1.9 KiB
JavaScript
import { openLocalDatabase } from './localDatabase.js'
|
|
import { performanceError, signature } from './performanceModel.js'
|
|
|
|
export const performanceKey = (date, period, exerciseId, format) => `${date}:${period}:${exerciseId}${format === 'emom-total' ? ':emom-total' : ''}`
|
|
async function transaction(mode, action) {
|
|
const db = await openLocalDatabase()
|
|
return new Promise((resolve, reject) => {
|
|
const tx = db.transaction('performanceEntries', mode)
|
|
let value
|
|
try {
|
|
const request = action(tx.objectStore('performanceEntries'))
|
|
if (request) request.onsuccess = () => { value = request.result }
|
|
} catch { tx.abort() }
|
|
tx.oncomplete = () => { db.close(); resolve(value ?? null) }
|
|
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not access detailed performance storage. Your changes were not saved.')) }
|
|
})
|
|
}
|
|
export async function readPerformance(date, period, exerciseId, format) {
|
|
const record = await transaction('readonly', (store) => store.get(performanceKey(date, period, exerciseId, format)))
|
|
if (record && performanceError(record)) throw new Error('The saved performance record is invalid or unsupported.')
|
|
return record
|
|
}
|
|
export async function writePerformance(record) {
|
|
const error = performanceError(record)
|
|
if (error) throw new Error(error)
|
|
await transaction('readwrite', (store) => store.put(record, performanceKey(record.date, record.period, record.exerciseId, record.format)))
|
|
}
|
|
export async function previousPerformance(date, period, definition, format) {
|
|
const records = await transaction('readonly', (store) => store.index('exercisePeriodFormat').getAll([definition.id, period, format]))
|
|
return (records ?? []).filter((record) => record.date < date && !performanceError(record) && signature(record.definition, record.format) === signature(definition, format) && record.rows.some((row) => row.completed))
|
|
.sort((a, b) => b.date.localeCompare(a.date))[0] ?? null
|
|
}
|