Files
knur-app/lib/models/strength.ts
Dominik Klarkowski 36407f534b init
2026-06-16 09:43:48 +02:00

67 lines
1.9 KiB
TypeScript

import { ObjectId } from "mongodb";
import { z } from "zod";
import { getDb } from "@/lib/db";
export const strengthSetSchema = z.object({
order: z.number().int().positive(),
weightKg: z.number().positive().optional(),
reps: z.number().int().positive().optional(),
});
export const strengthExerciseSchema = z.object({
name: z.string().min(1),
notes: z.string().optional(),
sets: z.array(strengthSetSchema),
});
export const strengthWorkoutSchema = z.object({
date: z.date(),
name: z.string().min(1),
notes: z.string().optional(),
exercises: z.array(strengthExerciseSchema),
sourceUrl: z.string().optional(),
sourceKey: z.string().min(1),
});
export type StrengthSet = z.infer<typeof strengthSetSchema>;
export type StrengthExercise = z.infer<typeof strengthExerciseSchema>;
export type StrengthWorkoutInput = z.infer<typeof strengthWorkoutSchema>;
export type StrengthWorkout = StrengthWorkoutInput & {
_id: ObjectId;
createdAt: Date;
};
const COLLECTION = "strength_workouts";
async function getCollection() {
const db = await getDb();
const collection = db.collection<StrengthWorkout>(COLLECTION);
await collection.createIndex({ sourceKey: 1 }, { unique: true });
return collection;
}
export async function upsertStrengthWorkout(
workout: StrengthWorkoutInput
): Promise<void> {
const collection = await getCollection();
await collection.updateOne(
{ sourceKey: workout.sourceKey },
{
$set: workout,
$setOnInsert: { createdAt: new Date() },
},
{ upsert: true }
);
}
export async function listStrengthWorkouts(): Promise<StrengthWorkout[]> {
const collection = await getCollection();
return collection.find().sort({ date: -1 }).toArray();
}
export async function getStrengthWorkout(id: string): Promise<StrengthWorkout | null> {
const collection = await getCollection();
return collection.findOne({ _id: new ObjectId(id) });
}