77 lines
2.0 KiB
Dart
77 lines
2.0 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:overfast_api/heroes/heroes_data.dart';
|
|
import 'package:overfast_api/maps/maps.dart';
|
|
import 'package:overfast_api/players/data_types.dart';
|
|
import 'package:overfast_api/players/player.dart';
|
|
import 'package:overfast_api/players/players.dart';
|
|
// import 'package:overfast_api/players/data_types.dart';
|
|
|
|
final fromJsonMap = <Type, Function(Map<String, dynamic>)>{
|
|
GameMap: GameMap.fromJson,
|
|
Map: (json) => json,
|
|
PlayerSummary: PlayerSummary.fromJson,
|
|
SearchResponse: SearchResponse.fromJson,
|
|
CareerProfile: CareerProfile.fromJson,
|
|
Hero: Hero.fromJson,
|
|
HeroDetails: HeroDetails.fromJson,
|
|
Roles: Roles.fromJson,
|
|
StatsSummary: StatsSummary.fromJson,
|
|
};
|
|
|
|
Future<T> Function<T>(String, [Map<String, dynamic>]) get(
|
|
http.Client client,
|
|
Uri baseUri,
|
|
) {
|
|
return <T>(
|
|
String path, [
|
|
Map<String, dynamic> params = const {},
|
|
]) async {
|
|
final uri = baseUri.replace(path: path, queryParameters: params);
|
|
final response = await client.get(uri);
|
|
|
|
throwIfNecessary(response.statusCode, response.body);
|
|
|
|
return fromJsonMap[T]!(json.decode(response.body));
|
|
};
|
|
}
|
|
|
|
Future<List<T>> Function<T>(String, [Map<String, dynamic>])
|
|
getList(
|
|
http.Client client,
|
|
Uri baseUri,
|
|
) {
|
|
return <T>(
|
|
String path, [
|
|
Map<String, dynamic> params = const {},
|
|
]) async {
|
|
final uri = baseUri.replace(path: path, queryParameters: params);
|
|
final response = await client.get(uri);
|
|
|
|
throwIfNecessary(response.statusCode, response.body);
|
|
|
|
return (json.decode(response.body) as List)
|
|
.map((e) => fromJsonMap[T]!(e)).cast<T>()
|
|
.toList();
|
|
};
|
|
}
|
|
|
|
void throwIfNecessary(int code, String body) {
|
|
if (code == 422) {
|
|
throw Exception('Invalid parameters\n${json.decode(body)['detail']}');
|
|
}
|
|
|
|
if (code == 500) {
|
|
throw Exception('Internal server error');
|
|
}
|
|
|
|
if (code == 504) {
|
|
throw Exception('Blizzard Server error');
|
|
}
|
|
|
|
if (code == 404) {
|
|
throw Exception('Not found\n${json.decode(body)['error']}');
|
|
}
|
|
}
|