70 lines
2.6 KiB
TypeScript
70 lines
2.6 KiB
TypeScript
import * as SQLite from 'expo-sqlite'
|
|
import { Measurement, SyncStatus } from '../types'
|
|
|
|
let db: SQLite.SQLiteDatabase | null = null
|
|
|
|
export async function initDatabase(): Promise<void> {
|
|
if (db) return
|
|
db = await SQLite.openDatabaseAsync('weegschaal.db')
|
|
await db.execAsync(`
|
|
CREATE TABLE IF NOT EXISTS measurements (
|
|
id TEXT PRIMARY KEY,
|
|
weight REAL NOT NULL,
|
|
bmi REAL NOT NULL,
|
|
bodyFatPercentage REAL NOT NULL,
|
|
fatMass REAL NOT NULL,
|
|
musclePercentage REAL NOT NULL,
|
|
muscleMass REAL NOT NULL,
|
|
visceralFat INTEGER NOT NULL,
|
|
bmr REAL NOT NULL,
|
|
measuredAt TEXT NOT NULL,
|
|
createdAt TEXT NOT NULL,
|
|
updatedAt TEXT NOT NULL,
|
|
syncStatus TEXT NOT NULL DEFAULT 'local'
|
|
);
|
|
`)
|
|
}
|
|
|
|
export async function insertMeasurement(m: Measurement): Promise<void> {
|
|
await db!.runAsync(
|
|
`INSERT INTO measurements (id, weight, bmi, bodyFatPercentage, fatMass, musclePercentage, muscleMass, visceralFat, bmr, measuredAt, createdAt, updatedAt, syncStatus)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
[m.id, m.weight, m.bmi, m.bodyFatPercentage, m.fatMass, m.musclePercentage, m.muscleMass, m.visceralFat, m.bmr, m.measuredAt, m.createdAt, m.updatedAt, m.syncStatus]
|
|
)
|
|
}
|
|
|
|
export async function getAllMeasurements(): Promise<Measurement[]> {
|
|
const rows = await db!.getAllAsync<any>(
|
|
'SELECT * FROM measurements ORDER BY measuredAt DESC'
|
|
)
|
|
return rows as Measurement[]
|
|
}
|
|
|
|
export async function getLatestMeasurement(): Promise<Measurement | null> {
|
|
const rows = await db!.getAllAsync<any>(
|
|
'SELECT * FROM measurements ORDER BY measuredAt DESC LIMIT 1'
|
|
)
|
|
return rows.length > 0 ? (rows[0] as Measurement) : null
|
|
}
|
|
|
|
export async function updateMeasurement(id: string, syncStatus: SyncStatus): Promise<void> {
|
|
await db!.runAsync(
|
|
'UPDATE measurements SET syncStatus = ?, updatedAt = ? WHERE id = ?',
|
|
[syncStatus, new Date().toISOString(), id]
|
|
)
|
|
}
|
|
|
|
export async function upsertMeasurement(m: Measurement): Promise<void> {
|
|
await db!.runAsync(
|
|
`INSERT OR REPLACE INTO measurements (id, weight, bmi, bodyFatPercentage, fatMass, musclePercentage, muscleMass, visceralFat, bmr, measuredAt, createdAt, updatedAt, syncStatus)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
[m.id, m.weight, m.bmi, m.bodyFatPercentage, m.fatMass, m.musclePercentage, m.muscleMass, m.visceralFat, m.bmr, m.measuredAt, m.createdAt, m.updatedAt, m.syncStatus]
|
|
)
|
|
}
|
|
|
|
export async function getUnsyncedMeasurements(): Promise<Measurement[]> {
|
|
const rows = await db!.getAllAsync<any>(
|
|
"SELECT * FROM measurements WHERE syncStatus = 'local' ORDER BY updatedAt ASC"
|
|
)
|
|
return rows as Measurement[]
|
|
}
|