userver: userver/formats/json/schema.hpp Source File
Loading...
Searching...
No Matches
schema.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/json/schema.hpp
4/// @brief JSON schema validator
5
6#include <string>
7#include <string_view>
8
9#include <userver/formats/json/exception.hpp>
10#include <userver/formats/json/value.hpp>
11#include <userver/utils/fast_pimpl.hpp>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace formats::json {
16
17/// @see formats::json::Schema::ValidationError::Throw
18class SchemaValidationException final : public ExceptionWithPath {
19 public:
22
23 std::string_view GetSchemaPath() const noexcept;
24
25 private:
27};
28
29/// @brief Contains a prepared JSON schema.
30///
31/// Usage example:
32/// @snippet formats/json/schema_test.cpp sample
33class Schema final {
34 public:
35 class ValidationResult;
36 class ValidationError;
37
38 explicit Schema(const Value& doc);
39 ~Schema() noexcept;
40
41 /// @brief Validates JSON against the Schema.
42 /// @returns ValidationResult describing the validation error, if any.
44
45 private:
46 struct Impl;
47 static constexpr std::size_t kSize = 288;
48 static constexpr std::size_t kAlignment = 8;
50};
51
52/// Contains error details (if any) from Schema::Validate.
53class Schema::ValidationResult final {
54 public:
55 /// Creates an `IsValid` result.
56 ValidationResult() noexcept;
57
60 ~ValidationResult() noexcept;
61
62 /// @returns `true` on validation success.
63 explicit operator bool() const noexcept;
64
65 /// @returns `true` on validation success.
66 bool IsValid() const noexcept;
67
68 /// @returns `true` on validation error.
69 bool IsError() const noexcept;
70
71 /// @throws SchemaValidationException on validation error.
72 /// @see Schema::ValidationResult::GetError
73 /// @see Schema::ValidationError::Throw
74 void ThrowIfError() &&;
75
76 /// @returns Validation error, `IsError` must be true.
78
79 private:
80 friend class Schema;
81 friend class ValidationError;
82
83 struct Impl;
84 static constexpr std::size_t kSize = 24;
85 static constexpr std::size_t kAlignment = 8;
87};
88
89class Schema::ValidationError final {
90 public:
91 /// @throws SchemaValidationException with error details.
92 /// @see Schema::ValidationResult::ThrowIfError
93 [[noreturn]] void Throw() const;
94
95 /// Describes the location within the validated JSON which violates
96 /// schema. The exact format of value path is unstable and should not
97 /// be relied upon.
99 /// Describes the location within the schema which was violated. The exact
100 /// format of schema path is unstable and should not be relied upon.
102 /// Describes the specifics of what condition was violated. The exact
103 /// format of details is unstable and should not be relied upon.
105
106 private:
107 friend class ValidationResult;
108
110
114};
115
116} // namespace formats::json
117
118USERVER_NAMESPACE_END