JSONSchema.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2015-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <folly/ExceptionWrapper.h>
  18. #include <folly/Range.h>
  19. #include <folly/dynamic.h>
  20. /**
  21. * Validation according to the draft v4 standard: http://json-schema.org/
  22. *
  23. * If your schema is invalid, then it won't validate anything. For example, if
  24. * you set "type": "invalid_type" in your schema, then it won't check for any
  25. * type, as if you had left that property out. If you want to make sure your
  26. * schema is valid, you can optionally validate it first according to the
  27. * metaschema.
  28. *
  29. * Limitations:
  30. * - We don't support fetching schemas via HTTP.
  31. * - We don't support remote $refs.
  32. * - We don't support $ref via id (only by path).
  33. * - We don't support UTF-8 for string lengths, i.e. we will count bytes for
  34. * schemas that use minLength/maxLength.
  35. */
  36. namespace folly {
  37. namespace jsonschema {
  38. /**
  39. * Interface for a schema validator.
  40. */
  41. struct Validator {
  42. virtual ~Validator() = 0;
  43. /**
  44. * Check whether the given value passes the schema. Throws if it fails.
  45. */
  46. virtual void validate(const dynamic& value) const = 0;
  47. /**
  48. * Check whether the given value passes the schema. Returns an
  49. * exception_wrapper indicating success or what the failure was.
  50. */
  51. virtual exception_wrapper try_validate(const dynamic& value) const
  52. noexcept = 0;
  53. };
  54. /**
  55. * Make a validator that can be used to check various json. Thread-safe.
  56. */
  57. std::unique_ptr<Validator> makeValidator(const dynamic& schema);
  58. /**
  59. * Makes a validator for schemas. You should probably check your schema with
  60. * this before you use makeValidator().
  61. */
  62. std::shared_ptr<Validator> makeSchemaValidator();
  63. } // namespace jsonschema
  64. } // namespace folly