From cbfaa67c1d73dab4f8d18c00dc2ec62a152fa303 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 21 Dec 2020 13:16:40 +0100 Subject: [PATCH] Move common code to base provider class --- lib/helpers/ui.dart | 1 - lib/providers/auth.dart | 8 +-- lib/providers/base_provider.dart | 101 +++++++++++++++++++++++++++++++ lib/providers/body_weight.dart | 72 ++++++---------------- 4 files changed, 120 insertions(+), 62 deletions(-) create mode 100644 lib/providers/base_provider.dart diff --git a/lib/helpers/ui.dart b/lib/helpers/ui.dart index 3734e55a..d4f77435 100644 --- a/lib/helpers/ui.dart +++ b/lib/helpers/ui.dart @@ -60,7 +60,6 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, BuildContext cont errorList.add(Text(value)); } } - //GlobalKey(debugLabel: 'wgerApp').currentContext showDialog( context: context, builder: (ctx) => AlertDialog( diff --git a/lib/providers/auth.dart b/lib/providers/auth.dart index fff135be..534abaae 100644 --- a/lib/providers/auth.dart +++ b/lib/providers/auth.dart @@ -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; // } diff --git a/lib/providers/base_provider.dart b/lib/providers/base_provider.dart new file mode 100644 index 00000000..92833210 --- /dev/null +++ b/lib/providers/base_provider.dart @@ -0,0 +1,101 @@ +/* + * This file is part of wger Workout Manager . + * 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 . + */ + +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> fetchAndSet(http.Client client) async { + if (client == null) { + client = http.Client(); + } + + // Send the request + final response = await client.get( + url + '?ordering=-date', + headers: { + '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; + } + + /// POSTs a new object + Future> add(Map 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 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; + } +} diff --git a/lib/providers/body_weight.dart b/lib/providers/body_weight.dart index de565c09..3d6f8574 100644 --- a/lib/providers/body_weight.dart +++ b/lib/providers/body_weight.dart @@ -16,26 +16,20 @@ * along with this program. If not, see . */ -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 _entries = []; - - BodyWeight(Auth auth, List entries) { - this._auth = auth; - this._entries = entries; - this._url = auth.serverUrl + nutritionPlansUrl; - } + BodyWeight(Auth auth, List entries) + : this._entries = entries, + super(auth, bodyWeightUrl); List 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: {'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; + final data = await fetchAndSet(client); final List 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 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();