UNPKG

mongoose-delete-ts

Version:
62 lines (61 loc) 2.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = default_1; function default_1(schema, methods) { schema.pre('save', function () { if (typeof this.deleted === 'undefined') { this.deleted = false; } }); const allMethods = getMethodsFromOptions(methods); if (allMethods.length > 0) { schema.pre(allMethods, async function () { if (deletedIsNotAlreadyInQuery(this)) { this.where({ deleted: false }); } }); } if (hasAggregateInOption(methods)) { schema.pre('aggregate', async function () { if (deletedIsNotAlreadyInAggregation(this)) { this.pipeline().unshift({ $match: { deleted: false } }); } }); } } function getMethodsFromOptions(methods) { if (methods === false) { return []; } else if (Array.isArray(methods)) { return methods; } return ['find', 'findOne', 'findOneAndUpdate', 'update', 'updateOne', 'updateMany', 'countDocuments']; } function hasAggregateInOption(methods) { if (methods === false) { return false; } else if (Array.isArray(methods)) { return methods.includes('aggregate'); } return true; } function deletedIsNotAlreadyInQuery(query) { return typeof query.getQuery().deleted === 'undefined'; } function deletedIsNotAlreadyInAggregation(aggregation) { const matches = aggregation.pipeline().filter(isPipelineMatch); return !matches.some((matchStage) => { const match = matchStage['$match']; const matchHasDeleted = Object.keys(match).includes('deleted'); if (matchHasDeleted) { return true; } const nested = Object.entries(match).filter(([key]) => key === '$or' || key === '$and'); return nested.some(([, array]) => array.some((value) => Object.keys(value).includes('deleted'))); }); } function isPipelineMatch(pipeline) { return Object.keys(pipeline).includes('$match'); }