Skip to content

Commit

Permalink
Fallback to a default value for document fields (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
elshize authored and amallia committed May 5, 2019
1 parent 1249ee9 commit 25ff64e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
16 changes: 16 additions & 0 deletions include/wapopp/detail.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,22 @@ namespace detail {
return std::get_if<T>(&v) != nullptr;
}

template <class T>
[[nodiscard]] auto read_field_or(nlohmann::json const &node,
std::string const &field,
T default_value) -> T
{
if (auto pos = node.find(field); pos != node.end()) {
try {
return pos->get<T>();
} catch (std::exception const &) {
return default_value;
}
} else {
return default_value;
}
}

template <class T>
[[nodiscard]] auto read_mandatory_field(nlohmann::json const &node, std::string const &field)
-> std::variant<T, Error>
Expand Down
12 changes: 6 additions & 6 deletions src/wapopp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ void append_content(nlohmann::json const &node, std::vector<Content> &contents,
}
}
return Record{data["id"],
data["article_url"],
data["title"],
data["author"],
data["type"],
data["source"],
data["published_date"],
detail::read_field_or<std::string>(data, "article_url", ""),
detail::read_field_or<std::string>(data, "title", ""),
detail::read_field_or<std::string>(data, "author", ""),
detail::read_field_or<std::string>(data, "type", ""),
detail::read_field_or<std::string>(data, "source", ""),
detail::read_field_or<std::uint64_t>(data, "published_date", 0u),
std::move(contents)};
} catch (nlohmann::detail::exception const& error) {
return Error{error.what(), line};
Expand Down
4 changes: 2 additions & 2 deletions test/test_wapopp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ TEST_CASE("Read record", "[unit]")
R"({"id": "b2e89334-33f9-11e1-825f-dabc29fd7071",)"
R"("article_url": "https://www.washingtonpost.com/truncated.html",)"
R"("title": "Danny Coale, Jarrett Boykin are a perfect 1-2 punch for Virginia Tech",)"
R"("author": "Mark Giannotto",)"
R"("author": null,)"
R"("published_date": 1325376562000,)"
R"("contents": [)"
R"({)"
Expand Down Expand Up @@ -79,7 +79,7 @@ TEST_CASE("Read record", "[unit]")
REQUIRE(record.id == j["id"]);
REQUIRE(record.url == j["article_url"]);
REQUIRE(record.title == j["title"]);
REQUIRE(record.author == j["author"]);
REQUIRE(record.author == "");
REQUIRE(record.published == j["published_date"]);
REQUIRE(record.type == j["type"]);
REQUIRE(record.source == j["source"]);
Expand Down

0 comments on commit 25ff64e

Please sign in to comment.