Skip to content

Commit

Permalink
fix: game phase db serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
eseidel committed Aug 12, 2024
1 parent f505964 commit f97552e
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
7 changes: 2 additions & 5 deletions packages/db/lib/db.dart
Original file line number Diff line number Diff line change
Expand Up @@ -681,15 +681,12 @@ class Database {
if (result.isEmpty) {
return null;
}
return GamePhase.values.firstWhere(
(phase) => phase.name == result[0][0] as String,
orElse: () => throw ArgumentError('Unknown game phase: ${result[0][0]}'),
);
return GamePhase.fromJson(result[0][0] as String);
}

Future<void> setGamePhase(GamePhase phase) async {
await executeSql('INSERT INTO config (key, value) VALUES (\'game_phase\', '
'\'$phase\') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value');
'\'${phase.toJson()}\') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value');
}

Future<String?> getAuthToken() async {
Expand Down
11 changes: 10 additions & 1 deletion packages/types/lib/src/game_phase.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,14 @@ enum GamePhase with EnumIndexOrdering {
exploration,

/// Sell off all our ships and retire.
selloff
selloff;

static GamePhase fromJson(String json) {
// TODO(eseidel): Remove on next reset.
final value = json.startsWith('GamePhase.') ? json.substring(10) : json;
return values.firstWhere((e) => e.name == value,
orElse: () => throw ArgumentError('Invalid json for GamePhase'));
}

String toJson() => name;
}
15 changes: 15 additions & 0 deletions packages/types/test/src/game_phase_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import 'package:test/test.dart';
import "package:types/types.dart";

void main() {
test('GamePhase json round trip', () {
final phase = GamePhase.bootstrap;
final json = phase.toJson();
final phase2 = GamePhase.fromJson(json);
expect(phase, phase2);

// Verify that our old JSON format still works, remove on next reset.
final phase3 = GamePhase.fromJson(phase.toString());
expect(phase, phase3);
});
}

0 comments on commit f97552e

Please sign in to comment.