74 lines
2.8 KiB
Dart
74 lines
2.8 KiB
Dart
import 'dart:math';
|
||
import 'package:fpdart/fpdart.dart';
|
||
import 'package:get_it/get_it.dart';
|
||
import 'package:http/http.dart' as http;
|
||
import 'package:maibu_satabot_v2/core/router/route_paths.dart';
|
||
import 'package:maibu_satabot_v2/features/auth/presentation/bloc/auth_cubit.dart';
|
||
import 'package:maibu_satabot_v2/features/my/repository/my_repository.dart';
|
||
import 'dart:convert';
|
||
|
||
import '../../../../core/di/injection.dart';
|
||
import '../../../../core/storage/user_storage.dart';
|
||
// 必须导入 DeviceFailure 类
|
||
import '../../../../features/devices/domain/errors/device_failure.dart';
|
||
|
||
class MyRepositoryImpl implements MyRepository {
|
||
// 可选:注入 UserStorage(如果需要获取 token 等用户信息)
|
||
final UserStorage _userStorage;
|
||
|
||
MyRepositoryImpl({UserStorage? userStorage}) : _userStorage = userStorage ?? sl<UserStorage>();
|
||
// 🔥 辅助方法:获取 Token
|
||
Future<String?> _getToken() async {
|
||
final user = await _userStorage.getUser();
|
||
return user?.token;
|
||
}
|
||
|
||
// 核心修复:严格匹配抽象类的方法签名
|
||
@override
|
||
Future<Either<DeviceFailure, int>> updateName(String nickName) async {
|
||
final url = Uri.parse('http://1.95.137.212:8081/system/user/profile');
|
||
|
||
// 补充:从 UserStorage 获取 token(接口通常需要认证)
|
||
final token = await _getToken();
|
||
// 1. Token 为空/无效:返回专属错误
|
||
if (token == null || token.isEmpty) {
|
||
// 异步执行登出(不阻塞当前方法返回)
|
||
Future.microtask(() async {
|
||
await GetIt.I<UserStorage>().deleteUser();
|
||
GetIt.I<AuthCubit>().logout();
|
||
});
|
||
return Left(DeviceFailure.serverError(message: '登录状态失效,请重新登录'));
|
||
}
|
||
final headers = {
|
||
'Content-Type': 'application/json',
|
||
'Authorization': 'Bearer $token', // 按需添加认证头
|
||
};
|
||
|
||
final body = jsonEncode({'nickName': nickName});
|
||
|
||
try {
|
||
final response = await http.put(url, headers: headers, body: body);
|
||
|
||
// 1. 处理成功响应(statusCode 200)
|
||
if (response.statusCode == 200) {
|
||
final data = jsonDecode(response.body) as Map<String, dynamic>;
|
||
|
||
// 根据接口返回值,返回 Either.right(成功码,比如 1 表示成功)
|
||
// 示例:假设接口返回 code=200 表示成功
|
||
final int successCode = data['code'] ?? 1;
|
||
return Right(successCode);
|
||
}
|
||
// 2. 处理失败响应(非 200 状态码)
|
||
else {
|
||
final String errorMsg = '修改昵称失败:状态码 ${response.statusCode}';
|
||
return Left(DeviceFailure.serverError(message: errorMsg));
|
||
}
|
||
}
|
||
// 3. 处理网络异常
|
||
catch (e) {
|
||
final String errorMsg = '网络异常:${e.toString()}';
|
||
return Left(DeviceFailure.serverError(message: errorMsg));
|
||
}
|
||
}
|
||
}
|