+/// object will be json_object_put
+int api_call(AFBClient *c, struct afb_wsj1 *wsj1, const char *verb,
+ json_object *object,
+ std::function<void(bool, json_object *)> onReply) {
+ TRACE();
+
+ // We need to wrap the actual onReply call once in order to
+ // *look* like a normal functions pointer (std::functions<>
+ // with captures cannot convert to function pointers).
+ // Alternatively we could setup a local struct and use it as
+ // closure, but I think it is cleaner this way.
+ int call_rc = 0;
+ bool returned = false;
+ std::function<void(bool, json_object *)> wrappedOnReply =
+ [&returned, &call_rc, &onReply](bool ok, json_object *j) {
+ TRACEN(wrappedOnReply);
+ call_rc = ok ? 0 : -EINVAL;
+ // We know it failed, but there may be an explanation in the
+ // json object.
+ {
+ TRACEN(onReply);
+ onReply(ok, j);
+ }
+ returned = true;
+ };
+
+ // make the actual call, use wrappedOnReply as closure
+ int rc = afb_wsj1_call_j(
+ wsj1, wmAPI, verb, object,
+ [](void *closure, afb_wsj1_msg *msg) {
+ TRACEN(callClosure);
+ auto *onReply =
+ reinterpret_cast<std::function<void(bool, json_object *)> *>(
+ closure);
+ (*onReply)(!!afb_wsj1_msg_is_reply_ok(msg),
+ afb_wsj1_msg_object_j(msg));
+ },
+ &wrappedOnReply);
+
+ if (rc < 0) {
+ fprintf(
+ stderr, "calling %s/%s(%s) failed: %m\n", wmAPI, verb,
+ json_object_to_json_string_ext(object, JSON_C_TO_STRING_PRETTY));
+ // Call the reply handler regardless with a NULL json_object*
+ onReply(false, nullptr);
+ } else {
+ // We need to dispatch until "returned" got set, this is necessary
+ // if events get triggered by the call (and would be dispatched before
+ // the actual call-reply).
+ while (!returned) {
+ dispatch_internal(c, -1);
+ }
+
+ // return the actual API call result
+ rc = call_rc;
+ }
+
+ return rc;
+}
+