refactor(models): migrate 28 data models to Zod schema-driven pattern
This commit is contained in:
@@ -2,40 +2,37 @@
|
||||
* 待同步的单条消息
|
||||
* 原始 Dart: SyncMessage (lib/data/models/chat/chat_sync.dart)
|
||||
*/
|
||||
export class SyncMessage {
|
||||
readonly role: string;
|
||||
readonly content: string;
|
||||
readonly timestamp: string;
|
||||
import { z } from "zod";
|
||||
|
||||
constructor(params: { role: string; content: string; timestamp: string }) {
|
||||
this.role = params.role;
|
||||
this.content = params.content;
|
||||
this.timestamp = params.timestamp;
|
||||
export const SyncMessageSchema = z.object({
|
||||
role: z.string(),
|
||||
content: z.string(),
|
||||
timestamp: z.string(),
|
||||
});
|
||||
|
||||
export type SyncMessageInput = z.input<typeof SyncMessageSchema>;
|
||||
export type SyncMessageData = z.output<typeof SyncMessageSchema>;
|
||||
|
||||
export class SyncMessage {
|
||||
declare readonly role: string;
|
||||
declare readonly content: string;
|
||||
declare readonly timestamp: string;
|
||||
|
||||
private constructor(input: SyncMessageInput) {
|
||||
const data = SyncMessageSchema.parse(input);
|
||||
Object.assign(this, data);
|
||||
Object.freeze(this);
|
||||
}
|
||||
|
||||
toJson(): Record<string, unknown> {
|
||||
return {
|
||||
role: this.role,
|
||||
content: this.content,
|
||||
timestamp: this.timestamp,
|
||||
};
|
||||
static from(input: SyncMessageInput): SyncMessage {
|
||||
return new SyncMessage(input);
|
||||
}
|
||||
|
||||
static fromJson(json: Record<string, unknown>): SyncMessage {
|
||||
const requireString = (key: string): string => {
|
||||
const v = json[key];
|
||||
if (typeof v !== "string") {
|
||||
throw new Error(
|
||||
`SyncMessage.${key} is required and must be a string`
|
||||
);
|
||||
}
|
||||
return v;
|
||||
};
|
||||
return new SyncMessage({
|
||||
role: requireString("role"),
|
||||
content: requireString("content"),
|
||||
timestamp: requireString("timestamp"),
|
||||
});
|
||||
static fromJson(json: unknown): SyncMessage {
|
||||
return SyncMessage.from(json as SyncMessageInput);
|
||||
}
|
||||
|
||||
toJson(): SyncMessageData {
|
||||
return SyncMessageSchema.parse(this);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user