first commit
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../core/network/api_exception.dart';
|
||||
import '../core/network/dio_client.dart';
|
||||
import '../models/auth_response.dart';
|
||||
|
||||
final authApiProvider = Provider<AuthApi>((ref) => AuthApi(ref.watch(dioProvider)));
|
||||
|
||||
class AuthApi {
|
||||
final Dio _dio;
|
||||
|
||||
AuthApi(this._dio);
|
||||
|
||||
/// 登录 → {token, username, nickname}
|
||||
Future<AuthResponse> login(String username, String password) async {
|
||||
try {
|
||||
final res = await _dio.post('/auth/login', data: {
|
||||
'username': username,
|
||||
'password': password,
|
||||
});
|
||||
return AuthResponse.fromJson(_map(res.data));
|
||||
} on DioException catch (e) {
|
||||
throw _unwrap(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// 注册 → {token, username, nickname}
|
||||
Future<AuthResponse> register(String username, String password, String nickname) async {
|
||||
try {
|
||||
final res = await _dio.post('/auth/register', data: {
|
||||
'username': username,
|
||||
'password': password,
|
||||
'nickname': nickname,
|
||||
});
|
||||
return AuthResponse.fromJson(_map(res.data));
|
||||
} on DioException catch (e) {
|
||||
throw _unwrap(e);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _map(Object? data) {
|
||||
if (data is Map<String, dynamic>) return data;
|
||||
throw ApiException(-1, '响应格式异常');
|
||||
}
|
||||
|
||||
Never _unwrap(DioException e) {
|
||||
final err = e.error;
|
||||
if (err is ApiException) throw err;
|
||||
throw ApiException(-1, '请求失败');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user