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