refactor(models): migrate 28 data models to Zod schema-driven pattern
This commit is contained in:
@@ -2,42 +2,38 @@
|
||||
* 登录响应
|
||||
* 原始 Dart: LoginResponse (lib/data/models/auth/auth_response.dart)
|
||||
*/
|
||||
import { User } from "../user/user";
|
||||
import { z } from "zod";
|
||||
import { User, UserSchema } from "../user/user";
|
||||
|
||||
export const LoginResponseSchema = z.object({
|
||||
user: UserSchema,
|
||||
token: z.string(),
|
||||
refreshToken: z.string().default(""),
|
||||
});
|
||||
|
||||
export type LoginResponseInput = z.input<typeof LoginResponseSchema>;
|
||||
export type LoginResponseData = z.output<typeof LoginResponseSchema>;
|
||||
|
||||
export class LoginResponse {
|
||||
readonly user: User;
|
||||
readonly token: string;
|
||||
readonly refreshToken: string;
|
||||
declare readonly user: User;
|
||||
declare readonly token: string;
|
||||
declare readonly refreshToken: string;
|
||||
|
||||
constructor(params: { user: User; token: string; refreshToken?: string }) {
|
||||
this.user = params.user;
|
||||
this.token = params.token;
|
||||
this.refreshToken = params.refreshToken ?? "";
|
||||
private constructor(input: LoginResponseInput) {
|
||||
const data = LoginResponseSchema.parse(input);
|
||||
Object.assign(this, data);
|
||||
Object.freeze(this);
|
||||
}
|
||||
|
||||
toJson(): Record<string, unknown> {
|
||||
return {
|
||||
user: this.user.toJson(),
|
||||
token: this.token,
|
||||
refreshToken: this.refreshToken,
|
||||
};
|
||||
static from(input: LoginResponseInput): LoginResponse {
|
||||
return new LoginResponse(input);
|
||||
}
|
||||
|
||||
static fromJson(json: Record<string, unknown>): LoginResponse {
|
||||
const token = json.token;
|
||||
if (typeof token !== "string") {
|
||||
throw new Error("LoginResponse.token is required and must be a string");
|
||||
}
|
||||
const userJson = json.user;
|
||||
if (typeof userJson !== "object" || userJson === null) {
|
||||
throw new Error("LoginResponse.user is required and must be an object");
|
||||
}
|
||||
return new LoginResponse({
|
||||
user: User.fromJson(userJson as Record<string, unknown>),
|
||||
token,
|
||||
refreshToken:
|
||||
typeof json.refreshToken === "string" ? json.refreshToken : undefined,
|
||||
});
|
||||
static fromJson(json: unknown): LoginResponse {
|
||||
return LoginResponse.from(json as LoginResponseInput);
|
||||
}
|
||||
|
||||
toJson(): LoginResponseData {
|
||||
return LoginResponseSchema.parse(this);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user