In this tutorial we will write a service that stores history of translation changes and returns the most recent translations. MongoDB would be used as a database. The service would have the following Rest API:
HTTP PATCH by path '/v1/translations' with query parameters 'key', 'lang' and 'value' updates a translation.
HTTP GET by path '/v1/translations' with query parameter 'last_update' returns unique translations that were added after the 'last_update'.
Note that the component holds a storages::mongo::PoolPtr - a client to the Mongo. That client is thread safe, you can use it concurrently from different threads and tasks.
Translations::InsertNew
In the Translations::InsertNew function we get the request arguments and form a BSON document for insertion.
MongoDB queries are just BSON documents. Each mongo document has an implicit _id field that stores the document creation time. Knowing that, we can use formats::bson::Oid::MakeMinimalFor() to find all the documents that were added after update_time. Query sorts the documents by modification times (by _id), so when the results are written into formats::json::ValueBuilder latter writes rewrite previous data for the same key.
All the values are described in a separate section Dynamic configs .
A production ready service would dynamically retrieve the above options at runtime from a configuration service. See Writing your own configs server for insights on how to change the above options on the fly, without restarting the service.
int main()
Finally, after writing down the dynamic config values into file at dynamic-config-fallbacks.fallback-path, we add our component to the components::MinimalServerComponentList(), and start the server with static configuration kStaticConfig.
To build the sample, execute the following build steps at the userver root directory:
mkdir build_release
cd build_release
cmake -DCMAKE_BUILD_TYPE=Release ..
make userver-samples-mongo_service
The sample could be started by running make start-userver-samples-mongo_service. The command would invoke testsuite start target that sets proper paths in the configuration files, prepares and starts the DB, and starts the service.
To start the service manually start the DB server and run ./samples/mongo_service/userver-samples-mongo_service -c </path/to/static_config.yaml> (do not forget to prepare the configuration files!).
Now you can send a request to your service from another terminal: