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
20 auto CreateHttpRequest(std::string action) const {
21 return http_client_.CreateRequest().url(service_url_).post().data(std::move(action)).perform();
22 }
23
24 static yaml_config::Schema GetStaticConfigSchema() {
26 type: object
27 description: My dependencies schema
28 additionalProperties: false
29 properties:
30 service-url:
31 type: string
32 description: URL of the service to send the actions to
33 )");
34 }
35
36private:
37 const std::string service_url_;
38 clients::http::Client& http_client_;
39};
40/// [ActionClient]
41
42/// [ActionDep]
43class ActionDep {
44public:
45 explicit ActionDep(const components::ComponentContext& config)
46 : component_{config.FindComponent<ActionClient>()}
47 {}
48 auto CreateActionRequest(std::string action) const { return component_.CreateHttpRequest(std::move(action)); }
49
50 static void RegisterOn(easy::HttpBase& app) {
51 app.TryAddComponent<ActionClient>(ActionClient::kName, "service-url: http://some-service.example/v1/action");
52 easy::HttpDep::RegisterOn(app);
53 }
54
55private:
56 ActionClient& component_;
57};
58/// [ActionDep]
59
60/// [main]
61int main(int argc, char* argv[]) {
62 using Deps = easy::Dependencies<ActionDep, easy::PgDep>;
63
64 easy::HttpWith<Deps>(argc, argv)
65 .DefaultContentType(http::content_type::kTextPlain)
66 .Post("/log", [](const server::http::HttpRequest& req, const Deps& deps) {
67 const auto& action = req.GetArg("action");
68 deps.pg().Execute(
70 "INSERT INTO events_table(action) VALUES($1)",
71 action
72 );
73 return deps.CreateActionRequest(action)->body();
74 });
75}
76/// [main]