| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- #include "projection.hpp"
- #include <sstream>
- namespace smartbotic::database {
- namespace {
- const std::vector<std::string> METADATA_FIELDS = {
- "_id", "_version", "_created_at", "_updated_at", "_created_by", "_updated_by"
- };
- std::vector<std::string> splitPath(const std::string& path) {
- std::vector<std::string> parts;
- std::stringstream ss(path);
- std::string part;
- while (std::getline(ss, part, '.')) {
- if (!part.empty()) parts.push_back(part);
- }
- return parts;
- }
- void copyPath(const nlohmann::json& src, nlohmann::json& dst,
- const std::vector<std::string>& parts, size_t idx) {
- if (idx >= parts.size()) return;
- const std::string& key = parts[idx];
- if (!src.is_object() || !src.contains(key)) return;
- if (idx == parts.size() - 1) {
- dst[key] = src[key];
- return;
- }
- if (!src[key].is_object()) {
- dst[key] = src[key];
- return;
- }
- if (!dst.contains(key) || !dst[key].is_object()) {
- dst[key] = nlohmann::json::object();
- }
- copyPath(src[key], dst[key], parts, idx + 1);
- }
- void deletePath(nlohmann::json& dst, const std::vector<std::string>& parts, size_t idx) {
- if (idx >= parts.size()) return;
- const std::string& key = parts[idx];
- if (!dst.is_object() || !dst.contains(key)) return;
- if (idx == parts.size() - 1) {
- dst.erase(key);
- return;
- }
- if (dst[key].is_object()) {
- deletePath(dst[key], parts, idx + 1);
- }
- }
- } // anonymous namespace
- nlohmann::json applyProjection(const nlohmann::json& document,
- const std::vector<std::string>& include,
- const std::vector<std::string>& exclude) {
- if (include.empty() && exclude.empty()) {
- return document;
- }
- if (!include.empty()) {
- nlohmann::json result = nlohmann::json::object();
- for (const auto& path : include) {
- auto parts = splitPath(path);
- if (parts.empty()) continue;
- copyPath(document, result, parts, 0);
- }
- for (const auto& meta : METADATA_FIELDS) {
- if (document.contains(meta)) {
- result[meta] = document[meta];
- }
- }
- return result;
- }
- nlohmann::json result = document;
- for (const auto& path : exclude) {
- auto parts = splitPath(path);
- if (parts.empty()) continue;
- if (parts.size() == 1) {
- bool isMeta = false;
- for (const auto& meta : METADATA_FIELDS) {
- if (parts[0] == meta) { isMeta = true; break; }
- }
- if (isMeta) continue;
- }
- deletePath(result, parts, 0);
- }
- return result;
- }
- } // namespace smartbotic::database
|