rpc: improve Notifier.send

This commit is contained in:
Felix Lange 2023-10-31 12:30:21 +01:00
parent 4180b5d442
commit 412aec48b8
2 changed files with 18 additions and 14 deletions

View file

@ -46,6 +46,17 @@ type subscriptionResult struct {
Result json.RawMessage `json:"result,omitempty"` Result json.RawMessage `json:"result,omitempty"`
} }
type subscriptionResultEnc struct {
ID string `json:"subscription"`
Result any `json:"result"`
}
type jsonrpcSubscriptionNotification struct {
Version string `json:"jsonrpc"`
Method string `json:"method"`
Params subscriptionResultEnc `json:"params"`
}
// A value of this type can a JSON-RPC request, notification, successful response or // A value of this type can a JSON-RPC request, notification, successful response or
// error response. Which one it is depends on the fields. // error response. Which one it is depends on the fields.
type jsonrpcMessage struct { type jsonrpcMessage struct {

View file

@ -176,23 +176,16 @@ func (n *Notifier) activate() error {
return nil return nil
} }
func (n *Notifier) send(sub *Subscription, data interface{}) error { func (n *Notifier) send(sub *Subscription, data any) error {
params := struct { msg := jsonrpcSubscriptionNotification{
ID string `json:"subscription"`
Result interface{} `json:"result,omitempty"`
}{ID: string(sub.ID), Result: data}
ctx := context.Background()
msg := struct {
Version string `json:"jsonrpc,omitempty"`
Method string `json:"method,omitempty"`
Params interface{} `json:"params,omitempty"`
}{
Version: vsn, Version: vsn,
Method: n.namespace + notificationMethodSuffix, Method: n.namespace + notificationMethodSuffix,
Params: params, Params: subscriptionResultEnc{
ID: string(sub.ID),
Result: data,
},
} }
return n.h.conn.writeJSON(ctx, msg, false) return n.h.conn.writeJSON(context.Background(), &msg, false)
} }
// A Subscription is created by a notifier and tied to that notifier. The client can use // A Subscription is created by a notifier and tied to that notifier. The client can use