projection.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include "projection.hpp"
  2. #include <sstream>
  3. namespace smartbotic::database {
  4. namespace {
  5. const std::vector<std::string> METADATA_FIELDS = {
  6. "_id", "_version", "_created_at", "_updated_at", "_created_by", "_updated_by"
  7. };
  8. std::vector<std::string> splitPath(const std::string& path) {
  9. std::vector<std::string> parts;
  10. std::stringstream ss(path);
  11. std::string part;
  12. while (std::getline(ss, part, '.')) {
  13. if (!part.empty()) parts.push_back(part);
  14. }
  15. return parts;
  16. }
  17. void copyPath(const nlohmann::json& src, nlohmann::json& dst,
  18. const std::vector<std::string>& parts, size_t idx) {
  19. if (idx >= parts.size()) return;
  20. const std::string& key = parts[idx];
  21. if (!src.is_object() || !src.contains(key)) return;
  22. if (idx == parts.size() - 1) {
  23. dst[key] = src[key];
  24. return;
  25. }
  26. if (!src[key].is_object()) {
  27. dst[key] = src[key];
  28. return;
  29. }
  30. if (!dst.contains(key) || !dst[key].is_object()) {
  31. dst[key] = nlohmann::json::object();
  32. }
  33. copyPath(src[key], dst[key], parts, idx + 1);
  34. }
  35. void deletePath(nlohmann::json& dst, const std::vector<std::string>& parts, size_t idx) {
  36. if (idx >= parts.size()) return;
  37. const std::string& key = parts[idx];
  38. if (!dst.is_object() || !dst.contains(key)) return;
  39. if (idx == parts.size() - 1) {
  40. dst.erase(key);
  41. return;
  42. }
  43. if (dst[key].is_object()) {
  44. deletePath(dst[key], parts, idx + 1);
  45. }
  46. }
  47. } // anonymous namespace
  48. nlohmann::json applyProjection(const nlohmann::json& document,
  49. const std::vector<std::string>& include,
  50. const std::vector<std::string>& exclude) {
  51. if (include.empty() && exclude.empty()) {
  52. return document;
  53. }
  54. if (!include.empty()) {
  55. nlohmann::json result = nlohmann::json::object();
  56. for (const auto& path : include) {
  57. auto parts = splitPath(path);
  58. if (parts.empty()) continue;
  59. copyPath(document, result, parts, 0);
  60. }
  61. for (const auto& meta : METADATA_FIELDS) {
  62. if (document.contains(meta)) {
  63. result[meta] = document[meta];
  64. }
  65. }
  66. return result;
  67. }
  68. nlohmann::json result = document;
  69. for (const auto& path : exclude) {
  70. auto parts = splitPath(path);
  71. if (parts.empty()) continue;
  72. if (parts.size() == 1) {
  73. bool isMeta = false;
  74. for (const auto& meta : METADATA_FIELDS) {
  75. if (parts[0] == meta) { isMeta = true; break; }
  76. }
  77. if (isMeta) continue;
  78. }
  79. deletePath(result, parts, 0);
  80. }
  81. return result;
  82. }
  83. } // namespace smartbotic::database