first commit
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
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/account.dart';
|
||||
|
||||
final accountApiProvider = Provider<AccountApi>((ref) => AccountApi(ref.watch(dioProvider)));
|
||||
|
||||
/// 账户接口(后端每个用户只有一个默认账户)
|
||||
class AccountApi {
|
||||
final Dio _dio;
|
||||
|
||||
AccountApi(this._dio);
|
||||
|
||||
/// 账户信息:余额、总收入、总支出(收支为全部账单汇总,只读)
|
||||
Future<AccountInfo> getAccount() async {
|
||||
try {
|
||||
final res = await _dio.get('/accounts');
|
||||
return AccountInfo.fromJson(_parseObject(res.data));
|
||||
} on DioException catch (e) {
|
||||
throw _unwrap(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新余额。
|
||||
///
|
||||
/// 注意:后端这个接口写入的是**期初余额**,传入前需用
|
||||
/// `initialBalanceFor()` 把目标余额换算成期初余额。
|
||||
Future<AccountInfo> updateBalance(double initialBalance) async {
|
||||
try {
|
||||
final res = await _dio.put('/accounts/balance', data: {
|
||||
'initialBalance': initialBalance,
|
||||
});
|
||||
return AccountInfo.fromJson(_parseObject(res.data));
|
||||
} on DioException catch (e) {
|
||||
throw _unwrap(e);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _parseObject(Object? data) {
|
||||
if (data is Map<String, dynamic>) return data;
|
||||
if (data is Map && data['data'] is Map) {
|
||||
return Map<String, dynamic>.from(data['data'] as Map);
|
||||
}
|
||||
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