From 323bd6cba4b9d70c0167f31699cccc9f7daf8d60 Mon Sep 17 00:00:00 2001 From: Yuta Uchijo <70194083+uchijo@users.noreply.github.com> Date: Wed, 22 Nov 2023 01:07:37 +0900 Subject: [PATCH] added MessageType enum and concreteType to Message (#39) --- lib/src/message.dart | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/lib/src/message.dart b/lib/src/message.dart index b142a94..7e3ed63 100644 --- a/lib/src/message.dart +++ b/lib/src/message.dart @@ -5,30 +5,32 @@ import 'package:nostr/nostr.dart'; // Used to deserialize any kind of message that a nostr client or relay can transmit. class Message { late String type; + late MessageType concreteType; late dynamic message; // nostr message deserializer Message.deserialize(String payload) { dynamic data = jsonDecode(payload); - var messages = ["EVENT", "REQ", "CLOSE", "NOTICE", "EOSE", "OK", "AUTH"]; - if (messages.contains(data[0]) == false) { + if (MessageType.values.map((e) => e.rawType).contains(data[0]) == + false) { throw 'Unsupported payload (or NIP)'; } type = data[0]; - switch (type) { - case "EVENT": + concreteType = MessageType.byRawType(data[0]); + switch (concreteType) { + case MessageType.event: message = Event.deserialize(data); // ignore: deprecated_member_use_from_same_package if (message.kind == 4) message = EncryptedDirectMessage(message); break; - case "OK": + case MessageType.ok: message = Nip20.deserialize(data); break; - case "REQ": + case MessageType.req: message = Request.deserialize(data); break; - case "CLOSE": + case MessageType.close: message = Close.deserialize(data); break; default: @@ -37,3 +39,19 @@ class Message { } } } + +enum MessageType { + event("EVENT"), + req("REQ"), + close("CLOSE"), + notice("NOTICE"), + eose("EOSE"), + ok("OK"), + auth("AUTH"); + + const MessageType(this.rawType); + final String rawType; + static MessageType byRawType(String name) { + return MessageType.values.byName(name.toLowerCase()); + } +}