userver: /data/code/userver/libraries/easy/samples/4_custom_dependency/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
9constexpr std::string_view kSchema = R"~(
10CREATE TABLE IF NOT EXISTS events_table (
11 id serial NOT NULL,
12 action VARCHAR PRIMARY KEY
13)
14)~";
15
16/// [ActionClient]
17class ActionClient : public components::ComponentBase {
18public:
19 static constexpr std::string_view kName = "action-client";
20
21 ActionClient(const components::ComponentConfig& config, const components::ComponentContext& context)
22 : ComponentBase{config, context},
23 service_url_(config["service-url"].As<std::string>()),
24 http_client_(context.FindComponent<components::HttpClient>().GetHttpClient())
25 {}
26
27 auto CreateHttpRequest(std::string action) const {
28 return http_client_.CreateRequest().url(service_url_).post().data(std::move(action)).perform();
29 }
30
31 static yaml_config::Schema GetStaticConfigSchema() {
33 type: object
34 description: My dependencies schema
35 additionalProperties: false
36 properties:
37 service-url:
38 type: string
39 description: URL of the service to send the actions to
40 )");
41 }
42
43private:
44 const std::string service_url_;
45 clients::http::Client& http_client_;
46};
47/// [ActionClient]
48
49/// [ActionDep]
50class ActionDep {
51public:
52 explicit ActionDep(const components::ComponentContext& config)
53 : component_{config.FindComponent<ActionClient>()}
54 {}
55 auto CreateActionRequest(std::string action) const { return component_.CreateHttpRequest(std::move(action)); }
56
57 static void RegisterOn(easy::HttpBase& app) {
58 app.TryAddComponent<ActionClient>(ActionClient::kName, "service-url: http://some-service.example/v1/action");
59 easy::HttpDep::RegisterOn(app);
60 }
61
62private:
63 ActionClient& component_;
64};
65/// [ActionDep]
66
67/// [main]
68int main(int argc, char* argv[]) {
69 using Deps = easy::Dependencies<ActionDep, easy::PgDep>;
70
71 easy::HttpWith<Deps>(argc, argv)
72 .DbSchema(kSchema)
73 .DefaultContentType(http::content_type::kTextPlain)
74 .Post("/log", [](const server::http::HttpRequest& req, const Deps& deps) {
75 const auto& action = req.GetArg("action");
76 deps.pg().Execute(
78 "INSERT INTO events_table(action) VALUES($1)",
79 action
80 );
81 return deps.CreateActionRequest(action)->body();
82 });
83}
84/// [main]