init
This commit is contained in:
66
lib/models/strength.ts
Normal file
66
lib/models/strength.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
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) });
|
||||
}
|
||||
Reference in New Issue
Block a user