refactor(models): migrate 28 data models to Zod schema-driven pattern
This commit is contained in:
@@ -1,59 +1,39 @@
|
||||
/**
|
||||
* 最近记忆模型
|
||||
* 原始 Dart: RecentMemory (lib/data/models/user/recent_memory.dart)
|
||||
*
|
||||
* 注:原始 Dart 中 `createdAt` 为 `String?`,按"全部非空"约定兜底为空串。
|
||||
*/
|
||||
export class RecentMemory {
|
||||
readonly type: string;
|
||||
readonly content: string;
|
||||
readonly importance: number;
|
||||
readonly createdAt: string;
|
||||
import { z } from "zod";
|
||||
|
||||
constructor(params: {
|
||||
type: string;
|
||||
content: string;
|
||||
importance: number;
|
||||
createdAt?: string;
|
||||
}) {
|
||||
this.type = params.type;
|
||||
this.content = params.content;
|
||||
this.importance = params.importance;
|
||||
this.createdAt = params.createdAt ?? "";
|
||||
export const RecentMemorySchema = z.object({
|
||||
type: z.string(),
|
||||
content: z.string(),
|
||||
importance: z.number(),
|
||||
createdAt: z.string().default(""),
|
||||
});
|
||||
|
||||
export type RecentMemoryInput = z.input<typeof RecentMemorySchema>;
|
||||
export type RecentMemoryData = z.output<typeof RecentMemorySchema>;
|
||||
|
||||
export class RecentMemory {
|
||||
declare readonly type: string;
|
||||
declare readonly content: string;
|
||||
declare readonly importance: number;
|
||||
declare readonly createdAt: string;
|
||||
|
||||
private constructor(data: RecentMemoryData) {
|
||||
Object.assign(this, data);
|
||||
Object.freeze(this);
|
||||
}
|
||||
|
||||
toJson(): Record<string, unknown> {
|
||||
return {
|
||||
type: this.type,
|
||||
content: this.content,
|
||||
importance: this.importance,
|
||||
createdAt: this.createdAt,
|
||||
};
|
||||
static from(input: RecentMemoryInput): RecentMemory {
|
||||
return new RecentMemory(RecentMemorySchema.parse(input));
|
||||
}
|
||||
|
||||
static fromJson(json: Record<string, unknown>): RecentMemory {
|
||||
const requireString = (key: string): string => {
|
||||
const v = json[key];
|
||||
if (typeof v !== "string") {
|
||||
throw new Error(
|
||||
`RecentMemory.${key} is required and must be a string`
|
||||
);
|
||||
}
|
||||
return v;
|
||||
};
|
||||
const importance = json.importance;
|
||||
if (typeof importance !== "number") {
|
||||
throw new Error(
|
||||
"RecentMemory.importance is required and must be a number"
|
||||
);
|
||||
}
|
||||
return new RecentMemory({
|
||||
type: requireString("type"),
|
||||
content: requireString("content"),
|
||||
importance,
|
||||
createdAt:
|
||||
typeof json.createdAt === "string" ? json.createdAt : undefined,
|
||||
});
|
||||
static fromJson(json: unknown): RecentMemory {
|
||||
return RecentMemory.from(json as RecentMemoryInput);
|
||||
}
|
||||
|
||||
toJson(): RecentMemoryData {
|
||||
return RecentMemorySchema.parse(this);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user