userver: /data/code/userver/libraries/easy/samples/3_json/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 "schemas/key_value.hpp"
5
6constexpr std::string_view kSchema = R"~(
7CREATE TABLE IF NOT EXISTS key_value_table (
8 key integer PRIMARY KEY,
9 value VARCHAR
10)
11)~";
12
13int main(int argc, char* argv[]) {
14 easy::HttpWith<easy::PgDep>(argc, argv)
15 .DbSchema(kSchema)
16 .Get(
17 "/kv",
18 [](formats::json::Value request_json, const easy::PgDep& dep) {
19 // Use generated parser for As()
20 auto key = request_json.As<schemas::KeyRequest>().key;
21
22 auto res = dep.pg().Execute(
23 storages::postgres::ClusterHostType::kSlave, "SELECT value FROM key_value_table WHERE key=$1", key
24 );
25
26 schemas::KeyValue response{key, res[0][0].As<std::string>()};
27 return formats::json::ValueBuilder{response}.ExtractValue();
28 }
29 )
30 .Post("/kv", [](formats::json::Value request_json, easy::PgDep dep) {
31 // Use generated parser for As()
32 auto key_value = request_json.As<schemas::KeyValue>();
33
34 dep.pg().Execute(
35 storages::postgres::ClusterHostType::kMaster,
36 "INSERT INTO key_value_table(key, value) VALUES($1, $2) ON CONFLICT (key) DO UPDATE SET value = $2",
37 key_value.key,
38 key_value.value
39 );
40
41 return formats::json::Value{};
42 });
43}