init
This commit is contained in:
62
lib/models/analysis.ts
Normal file
62
lib/models/analysis.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { ObjectId } from "mongodb";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export type AiAnalysisTargetType = "running" | "strength" | "dashboard";
|
||||
|
||||
export type AiAnalysisInput = {
|
||||
targetType: AiAnalysisTargetType;
|
||||
targetId: ObjectId;
|
||||
summary: string;
|
||||
tips: string[];
|
||||
model: string;
|
||||
};
|
||||
|
||||
export type AiAnalysis = AiAnalysisInput & {
|
||||
_id: ObjectId;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
const COLLECTION = "ai_analyses";
|
||||
|
||||
async function getCollection() {
|
||||
const db = await getDb();
|
||||
return db.collection<AiAnalysis>(COLLECTION);
|
||||
}
|
||||
|
||||
export async function saveAiAnalysis(input: AiAnalysisInput): Promise<AiAnalysis> {
|
||||
const collection = await getCollection();
|
||||
const doc = { ...input, _id: new ObjectId(), createdAt: new Date() };
|
||||
await collection.insertOne(doc);
|
||||
return doc;
|
||||
}
|
||||
|
||||
export async function getLatestAnalysisForTarget(
|
||||
targetType: AiAnalysisTargetType,
|
||||
targetId: ObjectId
|
||||
): Promise<AiAnalysis | null> {
|
||||
const collection = await getCollection();
|
||||
return collection.findOne({ targetType, targetId }, { sort: { createdAt: -1 } });
|
||||
}
|
||||
|
||||
export async function getLatestAnalysis(): Promise<AiAnalysis | null> {
|
||||
const collection = await getCollection();
|
||||
return collection.findOne({}, { sort: { createdAt: -1 } });
|
||||
}
|
||||
|
||||
const DASHBOARD_TARGET_ID = new ObjectId("000000000000000000000001");
|
||||
|
||||
export async function getDashboardAnalysis(): Promise<AiAnalysis | null> {
|
||||
const collection = await getCollection();
|
||||
return collection.findOne(
|
||||
{ targetType: "dashboard", targetId: DASHBOARD_TARGET_ID },
|
||||
{ sort: { createdAt: -1 } }
|
||||
);
|
||||
}
|
||||
|
||||
export async function saveDashboardAnalysis(
|
||||
summary: string,
|
||||
tips: string[],
|
||||
model: string
|
||||
): Promise<AiAnalysis> {
|
||||
return saveAiAnalysis({ targetType: "dashboard", targetId: DASHBOARD_TARGET_ID, summary, tips, model });
|
||||
}
|
||||
Reference in New Issue
Block a user