Skip to content

Commit

Permalink
feat: add EOSE class to obtain subscriptionId (#41)
Browse files Browse the repository at this point in the history
* added EOSE class

* added tests

* Message.deserialize handle EOSE
  • Loading branch information
uchijo committed Dec 11, 2023
1 parent 9eb32fa commit 29d80f5
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/nostr.dart
Expand Up @@ -4,6 +4,7 @@
library nostr;

export 'src/event.dart';
export 'src/eose.dart';
export 'src/keychain.dart';
export 'src/request.dart';
export 'src/filter.dart';
Expand Down
26 changes: 26 additions & 0 deletions lib/src/eose.dart
@@ -0,0 +1,26 @@
import 'dart:convert';

/// Indicates "end of stored events"
///
/// this class is mostly for getting subscription id
class Eose {
/// default constructor
Eose(this.subscriptionId);

/// subscription_id is a random string that should be used to represent a subscription.
final String subscriptionId;

/// Serialize to nostr close message
/// - ["EOSE", subscription_id]
String serialize() {
return jsonEncode(["EOSE", subscriptionId]);
}

/// Deserialize a nostr close message
/// - ["CLOSE", subscription_id]
factory Eose.deserialize(input) {
if (input is! List<dynamic>) throw 'Invalid type for EOSE message';
if (input.length != 2) throw 'Invalid length for EOSE message';
return Eose(input[1]);
}
}
3 changes: 3 additions & 0 deletions lib/src/message.dart
Expand Up @@ -32,6 +32,9 @@ class Message {
case MessageType.close:
message = Close.deserialize(data);
break;
case MessageType.eose:
message = Eose.deserialize(data);
break;
default:
message = jsonEncode(data.sublist(1));
break;
Expand Down
26 changes: 26 additions & 0 deletions test/eose_test.dart
@@ -0,0 +1,26 @@
import 'package:nostr/nostr.dart';
import 'package:test/test.dart';

void main() {
group('Eose', () {
test('Constructor', () {
String subscriptionId = generate64RandomHexChars();
var eose = Eose(subscriptionId);
expect(eose.subscriptionId, subscriptionId);
});

test('Eose.serialize', () {
String subscriptionId = generate64RandomHexChars();
String serialized = '["EOSE","$subscriptionId"]';
var eose = Eose(subscriptionId);
expect(eose.serialize(), serialized);
});

test('Eose.deserialize', () {
String subscriptionId = generate64RandomHexChars();
var serialized = ["EOSE", subscriptionId];
var eose = Eose.deserialize(serialized);
expect(eose.subscriptionId, subscriptionId);
});
});
}
1 change: 1 addition & 0 deletions test/message_test.dart
Expand Up @@ -35,6 +35,7 @@ void main() {
String payload = '["EOSE", "random"]';
var msg = Message.deserialize(payload);
expect(msg.type, "EOSE");
expect(msg.message.subscriptionId, "random");
});

test('OK', () {
Expand Down

0 comments on commit 29d80f5

Please sign in to comment.