Done login routine
This commit is contained in:
commit
f9b1b25e91
20 changed files with 983 additions and 0 deletions
94
lib/api/api_client.dart
Normal file
94
lib/api/api_client.dart
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:tuuli_app/api/model/access_token_model.dart';
|
||||
import 'package:http/browser_client.dart';
|
||||
import 'package:http/http.dart';
|
||||
|
||||
class ErrorOrData<T> {
|
||||
final T? data;
|
||||
final Exception? error;
|
||||
|
||||
ErrorOrData(this.data, this.error);
|
||||
|
||||
void unfold(
|
||||
void Function(T data) onData, void Function(Exception error) onError) {
|
||||
if (data != null) {
|
||||
onData(data as T);
|
||||
} else {
|
||||
onError(error!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
typedef FutureErrorOrData<T> = Future<ErrorOrData<T>>;
|
||||
|
||||
class ApiClient {
|
||||
final BrowserClient _client = BrowserClient();
|
||||
|
||||
final Uri baseUrl;
|
||||
|
||||
ApiClient(this.baseUrl);
|
||||
|
||||
ApiClient.fromString(String baseUrl) : this(Uri.parse(baseUrl));
|
||||
|
||||
FutureErrorOrData<AccessTokenModel> login(
|
||||
String username,
|
||||
String password,
|
||||
) async {
|
||||
AccessTokenModel? data;
|
||||
Exception? error;
|
||||
|
||||
final response = await post('/api/getAccessToken', body: {
|
||||
'username': username,
|
||||
'password': password,
|
||||
}, headers: {
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
if (response.statusCode == 200) {
|
||||
final body = json.decode(await response.stream.bytesToString());
|
||||
if (body['error'] != null) {
|
||||
error = Exception(body['error']);
|
||||
} else if (body['access_token'] == null) {
|
||||
error = Exception('No access token');
|
||||
} else {
|
||||
data = AccessTokenModel(accessToken: body['access_token']);
|
||||
}
|
||||
} else {
|
||||
error = Exception('HTTP ${response.statusCode}');
|
||||
}
|
||||
|
||||
return ErrorOrData(data, error);
|
||||
}
|
||||
|
||||
Future<StreamedResponse> get(
|
||||
String path, {
|
||||
Map<String, String>? headers,
|
||||
}) {
|
||||
return _request(path, 'GET', headers: headers);
|
||||
}
|
||||
|
||||
Future<StreamedResponse> post(
|
||||
String path, {
|
||||
Map<String, String>? headers,
|
||||
dynamic body,
|
||||
}) {
|
||||
return _request(path, 'POST', headers: headers, body: body);
|
||||
}
|
||||
|
||||
Future<StreamedResponse> _request(
|
||||
String path,
|
||||
String method, {
|
||||
Map<String, String>? headers,
|
||||
dynamic body,
|
||||
}) async {
|
||||
final uri = baseUrl.resolve(path);
|
||||
final request = Request(method, uri);
|
||||
if (headers != null) {
|
||||
request.headers.addAll(headers);
|
||||
}
|
||||
if (body != null) {
|
||||
request.body = json.encode(body);
|
||||
}
|
||||
return _client.send(request);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue