soft-delete-plugin-mongoose
Version:
a mongoose plugin that allows you to soft delete documents and restore them (for JS & TS)
83 lines (82 loc) • 2.69 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.overwriteAggregatePipeline = void 0;
/**
* Checks if a lookup stage is valid for soft delete filtering
*/
var isValidLookupStage = function (lookupStage) {
return !!(lookupStage.from &&
lookupStage.localField &&
lookupStage.foreignField &&
lookupStage.as &&
!lookupStage.localField.includes('.') // exclude nested lookups
);
};
/**
* Creates an $addFields stage to filter out soft deleted documents from lookup results
*/
var createSoftDeleteFilterStage = function (fieldName) {
var _a;
return {
$addFields: (_a = {},
_a[fieldName] = {
$filter: {
input: "$" + fieldName,
as: 'temp',
cond: { $ne: ['$$temp.isDeleted', true] },
},
},
_a),
};
};
/**
* Processes a $lookup stage and adds soft delete filtering if applicable
*/
var processLookupStage = function (stage, pipeline, index) {
var lookupStage = stage['$lookup'];
if (!lookupStage || !isValidLookupStage(lookupStage)) {
return;
}
var as = lookupStage.as;
var filterStage = createSoftDeleteFilterStage(as);
pipeline.splice(index + 1, 0, filterStage);
};
/**
* Processes a $match stage and adds soft delete filtering if needed
*/
var processMatchStage = function (stage, pipeline, index) {
var matchStage = stage['$match'];
if (!matchStage) {
return;
}
// Skip if already filtering for deleted documents
if (matchStage.isDeleted === true) {
return;
}
// Add soft delete filter to existing match conditions
pipeline[index]['$match'] = __assign(__assign({}, matchStage), { isDeleted: false });
};
/**
* Overwrites aggregation pipeline to handle soft deleted documents
* - Adds filtering for soft deleted documents in $lookup results
* - Ensures $match stages exclude soft deleted documents
*/
var overwriteAggregatePipeline = function (pipeline) {
pipeline.forEach(function (stage, index) {
processLookupStage(stage, pipeline, index);
processMatchStage(stage, pipeline, index);
});
return pipeline;
};
exports.overwriteAggregatePipeline = overwriteAggregatePipeline;