Skip to content

Commit

Permalink
feat: validate Data and Message models on construction (#1139)
Browse files Browse the repository at this point in the history
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
  • Loading branch information
ZauberNerd and sourcery-ai[bot] authored Jan 5, 2025
1 parent 0f5b982 commit 093c170
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
18 changes: 18 additions & 0 deletions lib/bademagic_module/models/data.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,27 @@ class Data {

// Convert JSON to Data object
factory Data.fromJson(Map<String, dynamic> json) {
if (!json.containsKey('messages')) {
throw Exception('Invalid JSON: Missing "messages" key');
}

if (json['messages'] is! List) {
throw Exception('Invalid JSON: "messages" must be a list');
}

if (json['messages'].isEmpty) {
throw Exception('Invalid JSON: "messages" list is empty');
}

var messagesFromJson = json['messages'] as List;

if (messagesFromJson.any((message) => message == null)) {
throw Exception('Invalid JSON: "messages" list contains null values');
}

List<Message> messageList =
messagesFromJson.map((message) => Message.fromJson(message)).toList();

return Data(messages: messageList);
}
}
27 changes: 24 additions & 3 deletions lib/bademagic_module/models/messages.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,31 @@ class Message {

// Convert JSON to Message object
factory Message.fromJson(Map<String, dynamic> json) {
if (!json.containsKey('text')) {
throw Exception('Invalid JSON: Message missing "text" key');
}

if (!json.containsKey('speed')) {
throw Exception('Invalid JSON: Message missing "speed" key');
}

if (!json.containsKey('mode')) {
throw Exception('Invalid JSON: Message missing "mode" key');
}

if (json['text'] is! List) {
throw Exception('Invalid JSON: "text" must be a list');
}

final textList = json['text'] as List;
if (textList.any((element) => element == null)) {
throw Exception('Invalid JSON: "text" list cannot contain null elements');
}

return Message(
text: List<String>.from(json['text']),
flash: json['flash'] as bool,
marquee: json['marquee'] as bool,
text: List<String>.from(textList),
flash: (json['flash'] as bool?) ?? false,
marquee: (json['marquee'] as bool?) ?? false,
speed: Speed.fromHex(
json['speed'] as String), // Using helper method for safety
mode: Mode.fromHex(
Expand Down

0 comments on commit 093c170

Please sign in to comment.