diff --git a/plugins/libplugin.c b/plugins/libplugin.c index 6b8aacfd5..0a88babe1 100644 --- a/plugins/libplugin.c +++ b/plugins/libplugin.c @@ -150,6 +150,37 @@ static struct json_stream *jsonrpc_stream_start(struct command *cmd) return js; } +struct json_stream *jsonrpc_stream_success(struct command *cmd) +{ + struct json_stream *js = jsonrpc_stream_start(cmd); + + json_object_start(js, "result"); + return js; +} + +struct json_stream *jsonrpc_stream_fail(struct command *cmd, + int code, + const char *err) +{ + struct json_stream *js = jsonrpc_stream_start(cmd); + + json_object_start(js, "error"); + json_add_member(js, "code", false, "%d", code); + json_add_string(js, "message", err); + + return js; +} + +struct json_stream *jsonrpc_stream_fail_data(struct command *cmd, + int code, + const char *err) +{ + struct json_stream *js = jsonrpc_stream_fail(cmd, code, err); + + json_object_start(js, "data"); + return js; +} + static struct command_result *command_complete(struct command *cmd, struct json_stream *result) { @@ -162,6 +193,15 @@ static struct command_result *command_complete(struct command *cmd, return &complete; } +struct command_result *WARN_UNUSED_RESULT +command_finished(struct command *cmd, struct json_stream *response) +{ + /* "result" or "error" object */ + json_object_end(response); + + return command_complete(cmd, response); +} + struct json_out *json_out_obj(const tal_t *ctx, const char *fieldname, const char *str) diff --git a/plugins/libplugin.h b/plugins/libplugin.h index 0518cc3e4..4bc5f682a 100644 --- a/plugins/libplugin.h +++ b/plugins/libplugin.h @@ -70,6 +70,25 @@ struct plugin_hook { const jsmntok_t *params); }; +/* Helper to create a JSONRPC2 response stream with a "result" object. */ +struct json_stream *jsonrpc_stream_success(struct command *cmd); + +/* Helper to create a JSONRPC2 response stream with an "error" object. */ +struct json_stream *jsonrpc_stream_fail(struct command *cmd, + int code, + const char *err); + +/* Helper to create a JSONRPC2 response stream with an "error" object, + * to which will be added a "data" object. */ +struct json_stream *jsonrpc_stream_fail_data(struct command *cmd, + int code, + const char *err); + +/* This command is finished, here's the response (the content of the + * "result" or "error" field) */ +struct command_result *WARN_UNUSED_RESULT +command_finished(struct command *cmd, struct json_stream *response); + /* Helper to create a zero or single-value JSON object; if @str is NULL, * object is empty. */ struct json_out *json_out_obj(const tal_t *ctx,