Move common code to base provider class

This commit is contained in:
Roland Geider
2020-12-21 13:16:40 +01:00
parent c9190cbb22
commit cbfaa67c1d
4 changed files with 120 additions and 62 deletions

View File

@@ -60,7 +60,6 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, BuildContext cont
errorList.add(Text(value));
}
}
//GlobalKey(debugLabel: 'wgerApp').currentContext
showDialog(
context: context,
builder: (ctx) => AlertDialog(

View File

@@ -27,8 +27,8 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:wger/models/http_exception.dart';
class Auth with ChangeNotifier {
String token;
String serverUrl;
String token = '';
String serverUrl = '';
// DateTime _expiryDate;
// String _userId;
// Timer _authTimer;
@@ -46,10 +46,6 @@ class Auth with ChangeNotifier {
// return null;
}
String get serverUrl2 {
return serverUrl;
}
// String get userId {
// return _userId;
// }

View File

@@ -0,0 +1,101 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) 2020 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* wger Workout Manager is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:wger/models/http_exception.dart';
import 'package:wger/providers/auth.dart';
/// Base provider class.
/// Provides a couple of comfort functions so we avoid a bit of boilerplate.
class WgerBaseProvider {
String url;
Auth auth;
WgerBaseProvider(auth, baseUrl) {
this.auth = auth;
this.url = auth.serverUrl + baseUrl;
}
/// Fetch and retrieve the overview list of objects, returns the JSON parsed response
Future<Map<String, dynamic>> fetchAndSet(http.Client client) async {
if (client == null) {
client = http.Client();
}
// Send the request
final response = await client.get(
url + '?ordering=-date',
headers: <String, String>{
'Authorization': 'Token ${auth.token}',
'User-Agent': 'wger Workout Manager App',
},
);
// Something wrong with our request
if (response.statusCode >= 400) {
throw WgerHttpException(response.body);
}
// Process the response
return json.decode(response.body) as Map<String, dynamic>;
}
/// POSTs a new object
Future<Map<String, dynamic>> add(Map<String, dynamic> data, http.Client client) async {
if (client == null) {
client = http.Client();
}
final response = await client.post(
url,
headers: {
'Authorization': 'Token ${auth.token}',
'Content-Type': 'application/json; charset=UTF-8',
'User-Agent': 'wger Workout Manager App',
},
body: json.encode(data),
);
// Something wrong with our request
if (response.statusCode >= 400) {
throw WgerHttpException(response.body);
}
return json.decode(response.body);
}
/// DELETEs an existing object
Future<Response> deleteRequest(int id, http.Client client) async {
final response = await client.delete(
'$url$id/',
headers: {
'Authorization': 'Token ${auth.token}',
'User-Agent': 'wger Workout Manager App',
},
);
// Something wrong with our request
if (response.statusCode >= 400) {
throw WgerHttpException(response.body);
}
return response;
}
}

View File

@@ -16,26 +16,20 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:wger/models/body_weight/weight_entry.dart';
import 'package:wger/models/http_exception.dart';
import 'package:wger/providers/auth.dart';
import 'package:wger/providers/base_provider.dart';
class BodyWeight with ChangeNotifier {
static const nutritionPlansUrl = '/api/v2/weightentry/';
class BodyWeight extends WgerBaseProvider with ChangeNotifier {
static const bodyWeightUrl = '/api/v2/weightentry/';
String _url;
Auth _auth;
List<WeightEntry> _entries = [];
BodyWeight(Auth auth, List<WeightEntry> entries) {
this._auth = auth;
this._entries = entries;
this._url = auth.serverUrl + nutritionPlansUrl;
}
BodyWeight(Auth auth, List<WeightEntry> entries)
: this._entries = entries,
super(auth, bodyWeightUrl);
List<WeightEntry> get items {
return [..._entries];
@@ -50,21 +44,10 @@ class BodyWeight with ChangeNotifier {
client = http.Client();
}
// Send the request
final response = await client.get(
_url + '?ordering=-date',
headers: <String, String>{'Authorization': 'Token ${_auth.token}'},
);
// Something wrong with our request
if (response.statusCode >= 400) {
throw WgerHttpException(response.body);
}
// Process the response
final extractedData = json.decode(response.body) as Map<String, dynamic>;
final data = await fetchAndSet(client);
final List<WeightEntry> loadedEntries = [];
for (final entry in extractedData['results']) {
for (final entry in data['results']) {
loadedEntries.add(WeightEntry.fromJson(entry));
}
@@ -77,30 +60,13 @@ class BodyWeight with ChangeNotifier {
client = http.Client();
}
try {
final response = await client.post(
_url,
headers: {
'Authorization': 'Token ${_auth.token}',
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode(entry.toJson()),
);
// Something wrong with our request
if (response.statusCode >= 400) {
throw WgerHttpException(response.body);
}
// Create entry and return
WeightEntry weightEntry = WeightEntry.fromJson(json.decode(response.body));
_entries.add(weightEntry);
_entries.sort((a, b) => a.date.compareTo(b.date));
notifyListeners();
return weightEntry;
} catch (error) {
throw error;
}
// Create entry and return it
final data = await add(entry.toJson(), client);
WeightEntry weightEntry = WeightEntry.fromJson(data);
_entries.add(weightEntry);
_entries.sort((a, b) => a.date.compareTo(b.date));
notifyListeners();
return weightEntry;
}
Future<void> deleteEntry(int id, {http.Client client}) async {
@@ -109,18 +75,14 @@ class BodyWeight with ChangeNotifier {
}
// Send the request and remove the entry from the list...
final url = '$_url$id/';
final existingEntryIndex = _entries.indexWhere((element) => element.id == id);
var existingWeightEntry = _entries[existingEntryIndex];
_entries.removeAt(existingEntryIndex);
notifyListeners();
final response = await client.delete(
url,
headers: {'Authorization': 'Token ${_auth.token}'},
);
final response = await deleteRequest(id, client);
// ...but it that didn't work, put it back again
// ...but that didn't work, put it back again
if (response.statusCode >= 400) {
_entries.insert(existingEntryIndex, existingWeightEntry);
notifyListeners();