Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: validate Data and Message models on construction #1139

Merged
merged 4 commits into from
Jan 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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(
sourcery-ai[bot] marked this conversation as resolved.
Show resolved Hide resolved
json['speed'] as String), // Using helper method for safety
mode: Mode.fromHex(
Expand Down
Loading