Skip to content

How to create and pass instances of new NatsMsg<T>() to the NatsConnection#PublishAsync<T>(in NatsMsg<T> msg....) API correctly? #632

@Farrukhjon

Description

@Farrukhjon

Proposed change

I want to use this API

NatsConnection#public ValueTask PublishAsync<T>(in NatsMsg<T> msg, INatsSerialize<T>? serializer = default, NatsPubOpts? opts = default, CancellationToken cancellationToken = default) =>
        PublishAsync(msg.Subject, msg.Data, msg.Headers, msg.ReplyTo, serializer, opts, cancellationToken);

to publish instances of NatsMsg<T>

But this requires from me to construct an instance of NatsMsg in "low level" manner:

new NatsMsg<T>(
                Subject: subject,
                Data: payload,
                Headers: headers,
                ReplyTo: replyTo,
                Connection: connection,
                Size: size
            );

If I understood correctly, API's doc hints to provide the Size of the message in such a way:

 int size = subject.Length + replyTo.Length + headers.Length + payload.Length;

But to achieve this, it seems, one needs to provide the headers parsed (since headers.Length is not compilable).

Question: How to create and pass instances of NatsMsg<T>() to the NatsConnection#PublishAsync<T>(in NatsMsg<T> msg....) API correctly?

I'm asking such question since I used nats-java version of this API but now want to transfer the java code consistently (without loosing API usage semantic) to C#/.Net platform.
https://github.com/nats-io/nats.java/blob/main/src/main/java/io/nats/client/impl/NatsMessage.java#L447

Message message = NatsMessage.builder()
            .subject(subject)
            .headers(headers)
            .replyTo(replyTo)
            .data(payload)
            .build();     
// and then publish it:
connection.jetStream().publish(message)            

Note that a user of the Nats Java API is not enforced to provide "Size" of the message up front.

Use case

Better user experience to call NatsConnection#PublishAsync<T>(in NatsMsg<T> msg....) API.

Contribution

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions