Skip to content

Commit

Permalink
added MessageType enum and concreteType to Message (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
uchijo authored Nov 21, 2023
1 parent cef5614 commit 323bd6c
Showing 1 changed file with 25 additions and 7 deletions.
32 changes: 25 additions & 7 deletions lib/src/message.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>((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:
Expand All @@ -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());
}
}

0 comments on commit 323bd6c

Please sign in to comment.