74 lines
2.0 KiB
Dart
74 lines
2.0 KiB
Dart
import 'dart:io';
|
|
import 'package:dio/dio.dart';
|
|
import 'package:social_app/core/api/i_api_client.dart';
|
|
import 'models/user_response.dart';
|
|
|
|
class UserBasicInfo {
|
|
final String id;
|
|
final String username;
|
|
final String? avatarUrl;
|
|
|
|
UserBasicInfo({required this.id, required this.username, this.avatarUrl});
|
|
|
|
factory UserBasicInfo.fromJson(Map<String, dynamic> json) {
|
|
return UserBasicInfo(
|
|
id: json['id'] as String,
|
|
username: json['username'] as String,
|
|
avatarUrl: json['avatar_url'] as String?,
|
|
);
|
|
}
|
|
}
|
|
|
|
class UsersApi {
|
|
final IApiClient _client;
|
|
static const _prefix = '/api/v1/users';
|
|
|
|
UsersApi(this._client);
|
|
|
|
Future<UserBasicInfo> getById(String userId) async {
|
|
final response = await _client.get('$_prefix/$userId');
|
|
return UserBasicInfo.fromJson(response.data);
|
|
}
|
|
|
|
Future<UserResponse> getMe() async {
|
|
final response = await _client.get('$_prefix/me');
|
|
return UserResponse.fromJson(response.data);
|
|
}
|
|
|
|
Future<UserResponse> updateMe(UserUpdateRequest request) async {
|
|
final response = await _client.patch('$_prefix/me', data: request.toJson());
|
|
return UserResponse.fromJson(response.data);
|
|
}
|
|
|
|
Future<String> uploadAvatar(File file) async {
|
|
final formData = FormData.fromMap({
|
|
'file': await MultipartFile.fromFile(
|
|
file.path,
|
|
filename: file.path.split('/').last,
|
|
),
|
|
});
|
|
final response = await _client.post<Map<String, dynamic>>(
|
|
'$_prefix/me/avatar',
|
|
data: formData,
|
|
);
|
|
final payload = response.data;
|
|
if (payload is! Map<String, dynamic>) {
|
|
throw StateError('Invalid /users/me/avatar response');
|
|
}
|
|
final url = payload['url'];
|
|
if (url is! String) {
|
|
throw StateError('Missing url in /users/me/avatar response');
|
|
}
|
|
return url;
|
|
}
|
|
|
|
Future<List<UserResponse>> searchUsers(String query) async {
|
|
final response = await _client.post(
|
|
'$_prefix/search',
|
|
data: {'query': query},
|
|
);
|
|
final List<dynamic> data = response.data;
|
|
return data.map((json) => UserResponse.fromJson(json)).toList();
|
|
}
|
|
}
|