userver: /data/code/userver/libraries/easy/samples/5_pg_service_template/src/main.cpp Source File
Loading...
Searching...
No Matches
main.cpp
1#include <userver/utest/using_namespace_userver.hpp> // Note: this is for the purposes of samples only
2
3#include <userver/easy.hpp>
4#include <userver/yaml_config/merge_schemas.hpp>
5
6#include <userver/clients/http/component.hpp>
7#include <userver/components/component_context.hpp>
8
9/// [ActionClient]
10class ActionClient : public components::ComponentBase {
11public:
12 static constexpr std::string_view kName = "action-client";
13
14 ActionClient(const components::ComponentConfig& config, const components::ComponentContext& context)
15 : ComponentBase{config, context},
16 service_url_(config["service-url"].As<std::string>()),
17 http_client_(context.FindComponent<components::HttpClient>().GetHttpClient()) {}
18
19 auto CreateHttpRequest(std::string action) const {
20 return http_client_.CreateRequest().url(service_url_).post().data(std::move(action)).perform();
21 }
22
23 static yaml_config::Schema GetStaticConfigSchema() {
24 return yaml_config::MergeSchemas<components::ComponentBase>(R"(
25 type: object
26 description: My dependencies schema
27 additionalProperties: false
28 properties:
29 service-url:
30 type: string
31 description: URL of the service to send the actions to
32 )");
33 }
34
35private:
36 const std::string service_url_;
37 clients::http::Client& http_client_;
38};
39/// [ActionClient]
40
41/// [ActionDep]
42class ActionDep {
43public:
44 explicit ActionDep(const components::ComponentContext& config) : component_{config.FindComponent<ActionClient>()} {}
45 auto CreateActionRequest(std::string action) const { return component_.CreateHttpRequest(std::move(action)); }
46
47 static void RegisterOn(easy::HttpBase& app) {
48 app.TryAddComponent<ActionClient>(ActionClient::kName, "service-url: http://some-service.example/v1/action");
49 easy::HttpDep::RegisterOn(app);
50 }
51
52private:
53 ActionClient& component_;
54};
55/// [ActionDep]
56
57/// [main]
58int main(int argc, char* argv[]) {
59 using Deps = easy::Dependencies<ActionDep, easy::PgDep>;
60
61 easy::HttpWith<Deps>(argc, argv)
62 .DefaultContentType(http::content_type::kTextPlain)
63 .Post("/log", [](const server::http::HttpRequest& req, const Deps& deps) {
64 const auto& action = req.GetArg("action");
65 deps.pg().Execute(
66 storages::postgres::ClusterHostType::kMaster, "INSERT INTO events_table(action) VALUES($1)", action
67 );
68 return deps.CreateActionRequest(action)->body();
69 });
70}
71/// [main]