shlink-manager/lib/API/Methods/get_short_urls.dart

70 lines
2.1 KiB
Dart
Raw Normal View History

2023-07-09 23:00:00 +02:00
import 'dart:async';
import 'dart:convert';
import 'package:dartz/dartz.dart';
import 'package:http/http.dart' as http;
2024-01-27 23:07:06 +01:00
import 'package:shlink_app/API/Classes/ShortURL/short_url.dart';
import '../server_manager.dart';
2023-07-09 23:00:00 +02:00
2024-01-27 23:07:06 +01:00
/// Gets all short URLs
2024-01-28 00:32:09 +01:00
FutureOr<Either<List<ShortURL>, Failure>> apiGetShortUrls(
String? apiKey, String? serverUrl, String apiVersion) async {
2024-01-27 23:07:06 +01:00
var currentPage = 1;
var maxPages = 2;
List<ShortURL> allUrls = [];
2023-07-09 23:00:00 +02:00
Failure? error;
2024-01-27 23:07:06 +01:00
while (currentPage <= maxPages) {
2024-01-28 00:32:09 +01:00
final response =
await _getShortUrlPage(currentPage, apiKey, serverUrl, apiVersion);
2023-07-09 23:00:00 +02:00
response.fold((l) {
2024-01-27 23:07:06 +01:00
allUrls.addAll(l.urls);
maxPages = l.totalPages;
currentPage++;
2023-07-09 23:00:00 +02:00
}, (r) {
2024-01-27 23:07:06 +01:00
maxPages = 0;
2023-07-09 23:00:00 +02:00
error = r;
});
}
if (error == null) {
2024-01-27 23:07:06 +01:00
return left(allUrls);
2024-01-28 00:32:09 +01:00
} else {
2023-07-09 23:00:00 +02:00
return right(error!);
}
}
2024-01-27 23:07:06 +01:00
/// Gets all short URLs from a specific page
2024-01-28 00:32:09 +01:00
FutureOr<Either<ShortURLPageResponse, Failure>> _getShortUrlPage(
int page, String? apiKey, String? serverUrl, String apiVersion) async {
2023-07-09 23:00:00 +02:00
try {
2024-01-28 00:32:09 +01:00
final response = await http.get(
Uri.parse("$serverUrl/rest/v$apiVersion/short-urls?page=$page"),
headers: {
"X-Api-Key": apiKey ?? "",
});
2023-07-09 23:00:00 +02:00
if (response.statusCode == 200) {
var jsonResponse = jsonDecode(response.body);
2024-01-28 00:32:09 +01:00
var pagesCount =
jsonResponse["shortUrls"]["pagination"]["pagesCount"] as int;
List<ShortURL> shortURLs =
(jsonResponse["shortUrls"]["data"] as List<dynamic>).map((e) {
2023-07-09 23:00:00 +02:00
return ShortURL.fromJson(e);
}).toList();
return left(ShortURLPageResponse(shortURLs, pagesCount));
2024-01-28 00:32:09 +01:00
} else {
2023-07-09 23:00:00 +02:00
try {
var jsonBody = jsonDecode(response.body);
2024-01-28 00:32:09 +01:00
return right(ApiFailure(
type: jsonBody["type"],
detail: jsonBody["detail"],
title: jsonBody["title"],
status: jsonBody["status"]));
} catch (resErr) {
2023-07-09 23:00:00 +02:00
return right(RequestFailure(response.statusCode, resErr.toString()));
}
}
2024-01-28 00:32:09 +01:00
} catch (reqErr) {
2023-07-09 23:00:00 +02:00
return right(RequestFailure(0, reqErr.toString()));
}
2024-01-28 00:32:09 +01:00
}