c++oat++

What is the correct way to use oatpp::Enum as a path parameter type in Endpoint?


I'm using Oat++ framework (https://oatpp.io/) to build a REST API. I want to manage user roles, and I want to have an endpoint to update a single field of a user record - the user role. To achieve this, I've created an end-point:

ENDPOINT("PUT", "/users/{userId}/role/{role}", updateUserRole,
         PATH(oatpp::String, userId),
         PATH(oatpp::String, role))
{
  // TODO - Set user role here.
  return createResponse(Status::CODE_200, "OK");
}

Now, I want to validate that the user role has a correct value. Specifically, that its value belongs to the set of allowed values. I could create some sort of a static set with predefined values and check if it contains the received value, but I wonder if there is a better way to this.

I've found that Oatpp has some oatpp::Enum type but I can't find any examples using enum in the endpoint as a path parameter.

So, is it possible to use oatpp::Enum as a path parameter? If yes, then what is the correct way of using it?

Thanks in advance!


Solution

  • Declare an Enum in the DTO code-gen section:

    ENUM(UserRoles, v_int32,
      VALUE(ADMIN, 1, "admin"), //<- you may use qualifiers here
      VALUE(GUEST, 2),
      VALUE(USER, 3)
    )
    

    Declare an endpoint:

    ENDPOINT("PUT", "/users/{userId}/role/{role}", updateUserRole,
             PATH(oatpp::String, userId),
             PATH(oatpp::Enum<UserRoles>, role))
    {
      // TODO - Set user role here.
      return createResponse(Status::CODE_200, "OK");
    }
    

    oatpp::Enum will do all validations for you.

    Valid request:

    $ curl -X PUT http://localhost:8000/users/user-1/role/GUEST
    OK
    

    Invalid request:

    $ curl -X PUT http://localhost:8000/users/user-1/role/SOMETHING
    server=oatpp/1.1.0
    code=400
    description=Bad Request
    message=Invalid PATH parameter 'role'. Expected type is 'oatpp::Enum<UserRoles>'
    

    You can also use oatpp::Enum<UserRoles>::AsNumber if you want to receive integer values.