This update is based on a previous review where I tried creating a WriteConfig
and a WriteConfigBuilder
. I have updated this so I am only using the Config
part and not the Builder
.
The wire protocol for Mongo Insert is:
You will notice that of the 7 parameters 5 are optional and one is implied due to context. So I have shaped my API so that the required parameters is part of the interface and the user can pass the optional parameters in a separate optional config object (Rather than having a mass of insert()
functions taking different number of parameters).
I am using this as an example. Because the findAndModify
API has 13 optional parameters (and I want to use a similar patter for all the API). If this looks sensible then I can use this standard pattern.
class Collection
{
... STUFF removed.
template<typename T>
InsertResult insert(std::vector<T> const& data, InsertConfig const& config = InsertConfig{});
template<typename... T>
InsertResult insert(std::tuple<T...> const& data, InsertConfig const& config = InsertConfig{});
};
The optional config object is then defined like this:
class InsertConfig
{
std::optional<bool> ordered;
std::optional<std::uint32_t> maxTimeMS;
std::optional<WriteConcern> writeConcern;
std::optional<bool> bypassDocumentValidation;
std::optional<std::string> comment;
public:
std::optional<bool> const& getOrdered() const {return ordered;}
std::optional<std::uint32_t> const& getMaxTimeMS() const {return maxTimeMS;}
std::optional<WriteConcern> const& getWriteConcern() const {return writeConcern;}
std::optional<bool> const& getBypassDocumentValidation() const {return bypassDocumentValidation;}
std::optional<std::string> const& getComment() const {return comment;}
InsertConfig& setOrdered(bool value) {ordered.emplace(value); return *this;}
InsertConfig& setMaxTimeMS(std::uint32_t value) {maxTimeMS.emplace(value); return *this;}
InsertConfig& setWriteConcern(WriteConcern value) {writeConcern.emplace(value); return *this;}
InsertConfig& setBypassDocumentValidation(bool value) {bypassDocumentValidation.emplace(value); return *this;}
InsertConfig& setComment(std::string value) {comment.emplace(value); return *this;}
};
This allows the interface to be called like this:
mongo["DB"]["Collection"].insert(peopleVector,
InsertConfig{}
.setOrdered(true)
.setComment("Add people")
// Add more optional param here
);
Nothing interesting to review in the actual insert()
function.