Non-generic AddEndpointAsync
mikoskinen opened this issue · 3 comments
Proposed change
AFAIK the current AddEndpointAsync implementation only has a generic version. So the endpoint is always typed.
Would it be possible to support a scenario where we could create an untyped endpoint? I would be happy if we could just get the Msg and then could manually convert the type.
Use case
We have some service endpoint's which may receive XML-data. In these cases we would like to use Linq to XML types like XDocument, XElement etc. to loop the data.
Contribution
I could perhaps help with the code.
At the moment you can use NatsMemoryOwner<byte>
(which uses memory pool when default serializer is in use) as your generic type to achieve what you described:
using System.Text;
using NATS.Client.Core;
using NATS.Client.Services;
var nats = new NatsConnection();
var svc = new NatsSvcContext(nats);
await using var s1 = await svc.AddServiceAsync("s1", "1.0.0");
await s1.AddEndpointAsync<NatsMemoryOwner<byte>>(
name: "greet",
handler: async msg =>
{
if (msg.Exception != null)
{
Console.Error.WriteLine("Error: " + msg.Exception.Message);
}
else
{
using var memoryOwner = msg.Data;
// use custom message serialization
var message = Encoding.UTF8.GetString(memoryOwner.Span);
Console.WriteLine($"Received: {message}");
await msg.ReplyAsync($"you said '{message}'");
}
});
Console.ReadLine();
//
// > nats req greet Hello
// 14:02:35 Sending request on "greet"
// 14:02:35 Received with rtt 904µs
// you said 'Hello'
//
Another option is to implement your own serializer: https://nats-io.github.io/nats.net.v2/documentation/serialization.html#using-custom-serializer
Excellent, thank you for the quick help.
thanks @mikoskinen 🙏 if you feel we can improve the api please feel free to make suggestions 💯 in a new issue or reopen this one.