oat++

oat++ async controller nonstatic member


Is async API act static? How I can access to member object?

#include OATPP_CODEGEN_BEGIN(ApiController)

class MyController : public oatpp::web::server::api::ApiController {
    public:
        ...
        
        ENDPOINT_INFO(root) {
            info->summary = "Example 'Root' endpoint. Without any params";
            info->addResponse<Object<MessageDto>>(Status::CODE_200, "application/json");
        }
        
        ENDPOINT_ASYNC("GET", "/hello", root){
            ENDPOINT_ASYNC_INIT(root)

            Action act() override {
                auto dto = MessageDto::createShared();
                dto->statusCode = 200;
                // if(data_proccessor_ != nullptr)
                // {

                // }
                data_proccessor_-> //**here is the error
                //a nonstatic member reference must be relative to a specific objectC/C++(245)**

                dto->message = "Hello World!";
                return _return(controller->createDtoResponse(Status::CODE_200, dto));
            }
                        
        };
    private:
        const std::shared_ptr<i_data_proccessor> data_proccessor_ = nullptr;
};

#include OATPP_CODEGEN_END(ApiController)

I have tried inject data processor object and use it in controller. Making the data processor as singleton not looks good for me. Any suggestions?


Solution

  • Each ENDPOINT coroutine has a controller variable - pointer to your controller. You have to also specify a correct type of that variable by adding

    typedef MyController __ControllerType;
    

    So the complete example is the following:

    class MyController : public oatpp::web::server::api::ApiController {
    private:
      typedef MyController __ControllerType;
    private:
      const std::shared_ptr<i_data_proccessor> data_proccessor_ = nullptr;
    public:
    
      ...
    
      ENDPOINT_ASYNC("GET", "/hello", root){
    
        ENDPOINT_ASYNC_INIT(root)
    
        Action act() override {
          if(controller->data_proccessor_) {
            controller->data_proccessor_->...
          }
          return _return(controller->createDtoResponse(Status::CODE_200, dto));
        }
                    
      };
      
    };