#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 <functional>
#include <stdexcept>
#include <string>
#include <vector>
#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 <class T>
static T req(const Json& j, const char* key) {
return convert<T>(child(j, key), key);
}
template <class T>
static std::optional<T> 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<T>(*it, key);
}
// Swift `?? default` on an optional wire field.
template <class T>
static T orDefault(const Json& j, const char* key, T fallback) {
auto v = opt<T>(j, key);
return v ? std::move(*v) : std::move(fallback);
}
static Date reqDate(const Json& j, const char* key);
static std::optional<Date> optDate(const Json& j, const char* key);
static Date toDate(const Json& value, const char* key);
template <class T>
static std::vector<T> reqList(const Json& j, const char* key, const std::function<T(const Json&)>& decode) {
return list<T>(child(j, key), key, decode);
}
template <class T>
static std::vector<T> optList(const Json& j, const char* key, const std::function<T(const Json&)>& decode) {
if (!j.is_object()) throw DecodeError("expected object");
auto it = j.find(key);
if (it == j.end() || it->is_null()) return {};
return list<T>(*it, key, decode);
}
template <class T>
static std::vector<T> list(const Json& array, const char* key, const std::function<T(const Json&)>& 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<T> out;
out.reserve(array.size());
for (const auto& item : array) out.push_back(decode(item));
return out;
}
template <class T>
static std::vector<T> reqModels(const Json& j, const char* key) {
return reqList<T>(j, key, [](const Json& item) { return T::fromJson(item); });
}
template <class T>
static T convert(const Json& value, const char* key) {
try {
return value.get<T>();
} catch (const Json::exception&) {
throw DecodeError(std::string("wrong type: ") + key);
}
}
};
} // namespace dp