#pragma once // Spec: models.md "General coding rules". Strict field access that mirrors Swift Decodable: // required key missing, null or of the wrong type throws DecodeError (the whole response is rejected); // optional key missing or null gives nullopt, a present key of the wrong type still throws. #include #include #include #include #include "core/Date.hpp" #include "core/Json.hpp" #include "spec/ModelLimits.hpp" namespace dp { class DecodeError : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class JsonDecode { public: static const Json& object(const Json& j, const char* what); static const Json& child(const Json& j, const char* key); // required, non-null template static T req(const Json& j, const char* key) { return convert(child(j, key), key); } template static std::optional opt(const Json& j, const char* key) { if (!j.is_object()) throw DecodeError("expected object"); auto it = j.find(key); if (it == j.end() || it->is_null()) return std::nullopt; return convert(*it, key); } // Swift `?? default` on an optional wire field. template static T orDefault(const Json& j, const char* key, T fallback) { auto v = opt(j, key); return v ? std::move(*v) : std::move(fallback); } static Date reqDate(const Json& j, const char* key); static std::optional optDate(const Json& j, const char* key); static Date toDate(const Json& value, const char* key); template static std::vector reqList(const Json& j, const char* key, const std::function& decode) { return list(child(j, key), key, decode); } template static std::vector optList(const Json& j, const char* key, const std::function& decode) { if (!j.is_object()) throw DecodeError("expected object"); auto it = j.find(key); if (it == j.end() || it->is_null()) return {}; return list(*it, key, decode); } template static std::vector list(const Json& array, const char* key, const std::function& decode) { if (!array.is_array()) throw DecodeError(std::string("expected array: ") + key); if (array.size() > spec::ModelLimits::kMaxListItems) throw DecodeError(std::string("array too long: ") + key); std::vector out; out.reserve(array.size()); for (const auto& item : array) out.push_back(decode(item)); return out; } template static std::vector reqModels(const Json& j, const char* key) { return reqList(j, key, [](const Json& item) { return T::fromJson(item); }); } template static T convert(const Json& value, const char* key) { try { return value.get(); } catch (const Json::exception&) { throw DecodeError(std::string("wrong type: ") + key); } } }; } // namespace dp