0

Let's say I have an entity "Address" and an entity "User" which are linked in a 1-n-Relationship. The client sends all the necessary data which is evaluated in my controller function.

The Controller Class declares the two required Mappers in the header file:

(auth.h)

namespace MDL = drogon_model::TestDB;

public:
  METHOD_LIST_BEGIN
    ADD_METHOD_TO(Authentication::registration, "/auth/register", Post,Options);
  METHOD_LIST_END
private:
  Mapper<MDL::User> userMapper = Mapper<MDL::User>(app().getFastDbClient());
  Mapper<MDL::Address> addressMapper = Mapper<MDL::Address>(app().getFastDbClient());

In the controller function I want to use the mapper's insert-method for both entities to asynchronously insert the data into the tables. Which is the correct C++ Way to await both inserts, for Address and User without nested callbacks? Usage of Libraries like RxCpp is welcome.

(auth.cc)

void Authentication::registration(const HttpRequestPtr& req,std::function<void (const HttpResponsePtr &)> &&callback) {
    Json::Value requestBody = *req->getJsonObject().get();
    MDL::User user(requestBody);
    userMapper.insert(user, [callback](const MDL::User &u) {
        LOG_DEBUG << "User Insert Success: ";
    }, [&isSuccess](const DrogonDbException &e) {
        LOG_DEBUG << e.base().what();
    });
    addressMapper.insert(address, [callback](const MDL::Address &a) {
        LOG_DEBUG << "Address Insert Success!";
    }, [](const DrogonDbException &e) {
        LOG_DEBUG << e.base().what();
    });
}

The Callbacks are of type std::function, but there is also a function "insertFuture" of type std::future available

Quirynn
  • 26
  • 2

1 Answers1

0

You could use the coroutine interface of CoroMapper<> to avoid using nested callbacks.

BTW: FastDbClient objects are strictly related to IO threads (Each io thread has its own FastDbClient object), so the app().getFastDbClient() method must be called in an IO thread (EventLoop), initialing Mappers in your code will lead to run-time errors. Please call the app().getFastDbClient() in requests handlers when using it.

eprom
  • 226
  • 2
  • 11