RIC-641 Add client/server model definitions
[ric-plt/xapp-frame-cpp.git] / src / rest / model / ModelBase.h
1 #ifndef XAPP_MODEL_ModelBase_H
2 #define XAPP_MODEL_ModelBase_H
3 #include <iostream>
4 #include <string.h>
5 #include <nlohmann/json.hpp>
6 #include <nlohmann/json-schema.hpp>
7 #include <type_traits>
8
9 using nlohmann::json_schema::json_validator;
10 using json = nlohmann::json;
11
12 namespace xapp {
13 namespace model {
14
15 std::invalid_argument invalid_parameter("Invalid Json Input");
16
17 template<typename ModelType>
18 bool _validate(const ModelType model) {
19     json _json = model;
20     json_validator validator;
21     validator.set_root_schema(model.validator_schema);
22
23     try {
24         validator.validate(_json);
25     } catch (const std::exception& e) {
26         std::cerr << "Struct Validation failed, here is why: " << e.what() << "\n";
27         throw;
28     }
29     return true;
30 }
31
32 struct ModelBase {
33     json validator_schema = R"(
34     {
35         "$schema": "http://json-schema.org/draft-07/schema#",
36         "title": "ModelBase"
37     })"_json;
38
39     bool validate_() {
40         return _validate(std::move(*this));
41     }
42
43     void validate_json(const json& _json) {
44         json_validator validator;
45         validator.set_root_schema(get_validator_schema());
46         try {
47             validator.validate(_json);
48         } catch (const std::exception& e) {
49             throw;
50         }
51         return;
52     }
53
54     virtual json get_validator_schema() const { return validator_schema; }
55 };
56
57 void from_json(const json& j, ModelBase& ref) {
58     return;
59 }
60 void to_json(json& j, const ModelBase& ref) {
61     return;
62 }
63
64 } /*model*/
65 } /*xapp*/
66 #endif /*XAPP_MODEL_ModelBase_H*/