CRUD working

This commit is contained in:
Odweta
2026-03-22 20:05:31 +01:00
parent 0219155f8e
commit a95d899ac5
11 changed files with 462 additions and 11 deletions
+72 -3
View File
@@ -1,7 +1,76 @@
// talks to the DB itself
// TODO: mock for now!
// TODO: implement the real one
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:frontend/model/quote.dart';
class QuoteRepository {
final String _dbBaseUrl = 'https://hlaskovnik-reimagined-latest.onrender.com';
static final String _apiBaseUrl = 'https://hlaskovnik-reimagined-latest.onrender.com';
static final String _apiKey = "2ogD5kc4sw3JVZoouQSV0w3LGRjSj5IjVFnAnk7IRCIK0ktONCeoOYinbNLSIHuU";
static final String _quotesEndpoint = '/quotes';
Future<List<Quote>> 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<Quote> 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<Quote> 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<void> 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');
}
}