feat(entry): 建立 MVVM+data 分层骨架,接入 V2 状态管理与 Navigation 路由
This commit is contained in:
33
entry/src/main/ets/data/api/UserApi.ets
Normal file
33
entry/src/main/ets/data/api/UserApi.ets
Normal file
@@ -0,0 +1,33 @@
|
||||
import { HttpClient, ApiResult, ApiError } from 'common';
|
||||
|
||||
/**
|
||||
* 后端用户接口 DTO(与后端字段约定对齐)。
|
||||
*/
|
||||
export class UserDto {
|
||||
id: string = '';
|
||||
name: string = '';
|
||||
email: string = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户相关网络请求服务:负责发请求、解析统一响应、返回 DTO。
|
||||
* TODO: BASE_URL 应改为环境注入(debug/release 分离)。
|
||||
*/
|
||||
export class UserApi {
|
||||
private static readonly BASE_URL: string = 'https://api.example.com';
|
||||
|
||||
private readonly http: HttpClient;
|
||||
|
||||
constructor(http: HttpClient) {
|
||||
this.http = http;
|
||||
}
|
||||
|
||||
async fetchUser(id: string): Promise<UserDto> {
|
||||
const raw = await this.http.get(`${UserApi.BASE_URL}/api/user/${id}`);
|
||||
const result = JSON.parse(raw) as ApiResult<UserDto>;
|
||||
if (!result.isSuccess()) {
|
||||
throw ApiError.business(result.code, result.message);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
35
entry/src/main/ets/data/repository/UserRepository.ets
Normal file
35
entry/src/main/ets/data/repository/UserRepository.ets
Normal file
@@ -0,0 +1,35 @@
|
||||
import { User } from '../../model/User';
|
||||
import { UserApi, UserDto } from '../api/UserApi';
|
||||
|
||||
/**
|
||||
* 用户数据仓库契约(抽象类):ViewModel 只依赖此契约,便于替换 mock/真实实现。
|
||||
* 注:用抽象类而非 interface,是为了在 ServiceLocator 中做 Object -> 契约 的强转时兼容 ArkTS。
|
||||
*/
|
||||
export abstract class UserRepository {
|
||||
abstract getUser(id: string): Promise<User>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 真实实现:调用 UserApi,做 DTO -> 领域模型映射。
|
||||
*/
|
||||
export class UserRepositoryImpl extends UserRepository {
|
||||
private readonly api: UserApi;
|
||||
|
||||
constructor(api: UserApi) {
|
||||
super();
|
||||
this.api = api;
|
||||
}
|
||||
|
||||
async getUser(id: string): Promise<User> {
|
||||
const dto: UserDto = await this.api.fetchUser(id);
|
||||
return UserRepositoryImpl.toDomain(dto);
|
||||
}
|
||||
|
||||
private static toDomain(dto: UserDto): User {
|
||||
const user = new User();
|
||||
user.id = dto.id;
|
||||
user.name = dto.name;
|
||||
user.email = dto.email;
|
||||
return user;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user