Properties.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2024, Tim Flynn <trflynn89@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/ByteString.h>
  8. #include <AK/JsonArray.h>
  9. #include <AK/JsonObject.h>
  10. #include <AK/JsonValue.h>
  11. #include <LibWeb/WebDriver/Error.h>
  12. namespace Web::WebDriver {
  13. template<typename PropertyType = ByteString>
  14. static ErrorOr<PropertyType, WebDriver::Error> get_property(JsonValue const& payload, StringView key)
  15. {
  16. if (!payload.is_object())
  17. return WebDriver::Error::from_code(ErrorCode::InvalidArgument, "Payload is not a JSON object");
  18. auto property = payload.as_object().get(key);
  19. if (!property.has_value())
  20. return WebDriver::Error::from_code(ErrorCode::InvalidArgument, ByteString::formatted("No property called '{}' present", key));
  21. if constexpr (IsSame<PropertyType, ByteString>) {
  22. if (!property->is_string())
  23. return WebDriver::Error::from_code(ErrorCode::InvalidArgument, ByteString::formatted("Property '{}' is not a String", key));
  24. return property->as_string();
  25. } else if constexpr (IsSame<PropertyType, bool>) {
  26. if (!property->is_bool())
  27. return WebDriver::Error::from_code(ErrorCode::InvalidArgument, ByteString::formatted("Property '{}' is not a Boolean", key));
  28. return property->as_bool();
  29. } else if constexpr (IsSame<PropertyType, u32>) {
  30. if (auto maybe_u32 = property->get_u32(); maybe_u32.has_value())
  31. return *maybe_u32;
  32. return WebDriver::Error::from_code(ErrorCode::InvalidArgument, ByteString::formatted("Property '{}' is not a Number", key));
  33. } else if constexpr (IsSame<PropertyType, JsonArray const*>) {
  34. if (!property->is_array())
  35. return WebDriver::Error::from_code(ErrorCode::InvalidArgument, ByteString::formatted("Property '{}' is not an Array", key));
  36. return &property->as_array();
  37. } else if constexpr (IsSame<PropertyType, JsonObject const*>) {
  38. if (!property->is_object())
  39. return WebDriver::Error::from_code(ErrorCode::InvalidArgument, ByteString::formatted("Property '{}' is not an Object", key));
  40. return &property->as_object();
  41. } else {
  42. static_assert(DependentFalse<PropertyType>, "get_property invoked with unknown property type");
  43. VERIFY_NOT_REACHED();
  44. }
  45. }
  46. }