Skip to content

Commit

Permalink
WIP: feat: APIs (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gustl22 committed Mar 22, 2024
1 parent 97a9444 commit d5ea1b2
Show file tree
Hide file tree
Showing 7 changed files with 143 additions and 7 deletions.
10 changes: 7 additions & 3 deletions wrestling_scoreboard_common/lib/src/services/api.dart
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
export 'reports/germany_nrw.dart';
import '../../common.dart';

export 'apis/germany_nrw.dart';

enum WrestlingApiProvider {
deNwRingenApi;

WrestlingApi get api {
switch (this) {
case WrestlingApiProvider.deNwRingenApi:
throw UnimplementedError();
return NrwGermanyWrestlingApi();
}
}
}

/// Abstraction for providing an api interface.
abstract class WrestlingApi {}
abstract class WrestlingApi {
Future<List<League>> importLeagues({int? season});
}
93 changes: 93 additions & 0 deletions wrestling_scoreboard_common/lib/src/services/apis/germany_nrw.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import 'dart:convert';

import 'package:http/http.dart' as http;

import '../../../common.dart';

extension NrwGermanyLeague on League {
static Future<League> fromJson(Map<String, dynamic> e, GetSingleOfTypeCallback getSingle) async {
final boutConfig = await getSingle<BoutConfig>(e['boutSchemeId'] as int);
return League(
id: e['id'] as int?,
name: e['name'] as String,
startDate: e['start_date'] as DateTime,
seasonPartitions: e['season_partitions'] as int,
boutConfig: boutConfig,
);
}
}

class NrwGermanyWrestlingApi extends WrestlingApi {
final _apiUrl = 'https://www.brv-ringen.de/Api/v1/cs/';

@override
Future<List<League>> importLeagues({int? season}) async {
return await _getLeagueList(seasonId: season?.toString());
}

static Future<T> getSingleFromDataType<T extends DataObject>(int id) {
// return getControllerFromDataType(T).getSingle(id) as Future<T>;
throw UnimplementedError();
}

/// Get all seasons
Future<List<String>> _getSeasonList() async {
final uri = Uri.parse(_apiUrl).replace(queryParameters: {
'op': 'listSaison',
});
final response = await http.get(uri);
if (response.statusCode == 200) {
final Map<String, dynamic> json = jsonDecode(response.body);
final Map<String, dynamic> competitionList = json['ligaList'];
return await Future.wait(competitionList.entries.map((entry) async => entry.value.toString()));
} else {
throw Exception('Failed to get the saison list: ${response.reasonPhrase ?? response.statusCode.toString()}');
}
}

/// Get leagues of a season
Future<List<League>> _getLeagueList({
String? seasonId,
}) async {
seasonId ??= DateTime.now().year.toString();
final uri = Uri.parse(_apiUrl).replace(queryParameters: {
'op': 'listLiga',
'sid': seasonId,
});
final response = await http.get(uri);
if (response.statusCode == 200) {
final Map<String, dynamic> json = jsonDecode(response.body);
final Map<String, dynamic> ligaList = json['ligaList'];
return await Future.wait(
ligaList.entries.map((entry) => NrwGermanyLeague.fromJson(entry.value, getSingleFromDataType)));
} else {
throw Exception(
'Failed to get the liga list (seasonId: $seasonId): ${response.reasonPhrase ?? response.statusCode.toString()}');
}
}

/// Get team matches of a league
Future<List<League>> _getCompetitionList({
String? seasonId,
String ligaId = 'Gruppenliga',
String regionId = 'Süd',
}) async {
seasonId ??= DateTime.now().year.toString();
final uri = Uri.parse(_apiUrl).replace(queryParameters: {
'op': 'listCompetition',
'sid': seasonId,
'ligaId': ligaId,
'rid': regionId,
});
final response = await http.get(uri);
if (response.statusCode == 200) {
final Map<String, dynamic> json = jsonDecode(response.body);
final Map<String, dynamic> competitionList = json['competitionList'];
return await Future.wait(
competitionList.entries.map((entry) => NrwGermanyLeague.fromJson(entry.value, getSingleFromDataType)));
} else {
throw Exception(
'Failed to get the competition list (seasonId: $seasonId, ligaId: $ligaId, rid: $regionId): ${response.reasonPhrase ?? response.statusCode.toString()}');
}
}
}
1 change: 1 addition & 0 deletions wrestling_scoreboard_common/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ dependencies:
json_annotation: ^4.8.1
freezed_annotation: ^2.4.1
country: ^4.1.3
http: ^1.2.1

dev_dependencies:
build_runner: ^2.3.0
Expand Down
15 changes: 15 additions & 0 deletions wrestling_scoreboard_common/test/services/apis_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import 'package:test/test.dart';
import 'package:wrestling_scoreboard_common/common.dart';

void main() {
group('APIs', () {
test('Germany, NRW', () async {
final wrestlingApi = WrestlingApiProvider.deNwRingenApi.api;
final leagues = await wrestlingApi.importLeagues(season: 2023);
expect(
leagues,
'',
);
});
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ void main() {

group('Reports', () {
test('Germany, NRW', () {
final wrestlingReport = NrwGermanyWrestlingReporter();
final wrestlingReport = WrestlingReportProvider.deNwRdb274.reporter;
final report = wrestlingReport.exportTeamMatchReport(
teamMatch,
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import 'package:shelf/shelf.dart';
import 'package:wrestling_scoreboard_common/common.dart';

import 'entity_controller.dart';

class ServiceController {
Future<Response> import(Request request, String provider) async {
final apiProvider = WrestlingApiProvider.values.byName(provider);
try {
final leagues = await apiProvider.api.importLeagues(season: 2023);
// Iterable<EntityController> entityControllers =
// dataTypes.map((t) => EntityController.getControllerFromDataType(t));
// await Future.forEach(entityControllers, (e) => e.deleteMany());
return Response.ok('{"status": "success"}');
} catch (err) {
return Response.internalServerError(body: '{"err": "$err"}');
}
}
}
10 changes: 7 additions & 3 deletions wrestling_scoreboard_server/lib/routes/api_route.dart
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:wrestling_scoreboard_server/controllers/database_controller.dart';
import 'package:wrestling_scoreboard_server/controllers/league_team_participation_controller.dart';
import 'package:wrestling_scoreboard_server/controllers/division_weight_class_controller.dart';

import '../controllers/bout_action_controller.dart';
import '../controllers/bout_config_controller.dart';
import '../controllers/bout_controller.dart';
import '../controllers/club_controller.dart';
import '../controllers/competition_bout_controller.dart';
import '../controllers/competition_controller.dart';
import '../controllers/database_controller.dart';
import '../controllers/organization_controller.dart';
import '../controllers/division_controller.dart';
import '../controllers/league_controller.dart';
import '../controllers/league_team_participation_controller.dart';
import '../controllers/league_weight_class_controller.dart';
import '../controllers/lineup_controller.dart';
import '../controllers/membership_controller.dart';
import '../controllers/participant_state_controller.dart';
import '../controllers/participation_controller.dart';
import '../controllers/person_controller.dart';
import '../controllers/service_controller.dart';
import '../controllers/team_controller.dart';
import '../controllers/team_match_bout_controller.dart';
import '../controllers/team_match_controller.dart';
Expand All @@ -35,6 +36,9 @@ class ApiRoute {
router.post('/database/restore', databaseController.restore);
router.post('/database/restore_default', databaseController.restoreDefault);

final serviceController = ServiceController();
router.post('/service/api/<provider>/import', serviceController.import);

final boutConfigController = BoutConfigController();
router.post('/bout_config', boutConfigController.postSingle);
router.get('/bout_configs', boutConfigController.requestMany);
Expand Down

0 comments on commit d5ea1b2

Please sign in to comment.