|
| 1 | +import 'package:dio/dio.dart'; |
| 2 | +import 'package:flutter/foundation.dart'; |
| 3 | + |
| 4 | +import '../models/user_model.dart'; |
| 5 | + |
| 6 | +abstract class AuthRepository { |
| 7 | + Future<UserModel> login(String email, String password); |
| 8 | + Future<UserModel> register(Map<String, dynamic> userData); |
| 9 | +} |
| 10 | + |
| 11 | +class AuthRepositoryImpl implements AuthRepository { |
| 12 | + final Dio _dio; |
| 13 | + |
| 14 | + AuthRepositoryImpl(this._dio); |
| 15 | + |
| 16 | + @override |
| 17 | + Future<UserModel> login(String email, String password) async { |
| 18 | + try { |
| 19 | + final response = await _dio.post( |
| 20 | + '/auth/v1/token', |
| 21 | + queryParameters: {'grant_type': 'password'}, |
| 22 | + data: {'email': email, 'password': password}, |
| 23 | + ); |
| 24 | + |
| 25 | + if (response.statusCode == 200) { |
| 26 | + return UserModel.fromJson(response.data['user']); |
| 27 | + } else { |
| 28 | + throw Exception('An error occurred'); |
| 29 | + } |
| 30 | + } on DioError catch (e) { |
| 31 | + throw await Future.error(e.response!.data['error_description']); |
| 32 | + } catch (e) { |
| 33 | + debugPrint('AuthRepositoryImpl.login: $e'); |
| 34 | + throw await Future.error("Couldn't login. Is the device online?"); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + @override |
| 39 | + Future<UserModel> register(Map<String, dynamic> userData) async { |
| 40 | + try { |
| 41 | + final response = await _dio.post('/auth/v1/signup', data: userData); |
| 42 | + return UserModel.fromJson(response.data); |
| 43 | + } on DioError catch (e) { |
| 44 | + if (e.response!.statusCode == 400) { |
| 45 | + throw await Future.error(e.response!.data['error_description']); |
| 46 | + } else { |
| 47 | + throw await Future.error(e.message); |
| 48 | + } |
| 49 | + } catch (e, stack) { |
| 50 | + debugPrint('Error: $e\nStack : $stack'); |
| 51 | + throw await Future.error("Couldn't register. Is the device online?"); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments