import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:frontend/model/quote.dart'; class QuoteRepository { static final String _realApiBaseUrl = 'https://hlaskovnik-reimagined-latest.onrender.com'; //static final String _testApiBaseUrl = 'http://localhost:8080'; static final String _apiBaseUrl = _realApiBaseUrl; static final String _apiKey = "2ogD5kc4sw3JVZoouQSV0w3LGRjSj5IjVFnAnk7IRCIK0ktONCeoOYinbNLSIHuU"; static final String _quotesEndpoint = '/quotes'; Future> readQuotes() async { final url = Uri.parse(_apiBaseUrl+_quotesEndpoint); final headers = { 'Authorization' : 'Bearer $_apiKey', 'Content-Type': 'application/json', }; final response = await http.get(url, headers: headers); if (response.statusCode == 200) { final List data = jsonDecode(response.body); return data.map((json) => Quote.fromJson(json)).toList(); } else { throw Exception('failed to read quotes from database'); } } Future createQuote(Quote quote) async { final url = Uri.parse(_apiBaseUrl+_quotesEndpoint); final body = jsonEncode({'author' : quote.author, 'body' : quote.body}); final headers = { 'Authorization' : 'Bearer $_apiKey', 'Content-Type': 'application/json', }; final response = await http.post(url, body: body, headers: headers); if (response.statusCode == 200 || response.statusCode == 201) { return Quote.fromJson(jsonDecode(response.body)); } else { throw Exception('failed to add quote to database'); } } Future updateQuote(Quote quote) async { final url = Uri.parse('$_apiBaseUrl$_quotesEndpoint/${quote.id}'); final body = jsonEncode({'body' : quote.body, 'author' : quote.author}); final headers = { 'Authorization' : 'Bearer $_apiKey', 'Content-Type': 'application/json', }; final response = await http.put(url, body: body, headers: headers); if (response.statusCode == 200) { return Quote.fromJson(jsonDecode(response.body)); } if (response.statusCode == 204) { return quote; } throw Exception('failed to update quote in database'); } Future deleteQuote(Quote quote) async { final url = Uri.parse('$_apiBaseUrl$_quotesEndpoint/${quote.id}'); final headers = { 'Authorization' : 'Bearer $_apiKey', 'Content-Type': 'application/json', }; final response = await http.delete(url, headers: headers); if (response.statusCode == 200 || response.statusCode == 204) { return; } throw Exception('failed to delete quote from database'); } }