Skip to content

.lean() with post-hook of .find and .findOne #65

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion lib/mongoose-field-encryption.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,13 @@ const fieldEncryption = function (schema, options) {
}
};

function getCompatitibleNextFunc(next) {
function getCompatitibleNextFunc(next, data) {
// ! For the post-hook for .find and .findOne data is the first argument,
// ! therefore checking for an object in the first argument resolves the
// ! second argument to be next().
if (typeof next === "object" && typeof data === "function") {
return data;
}
if (typeof next !== "function") {
return defaultNext;
}
Expand All @@ -122,6 +128,12 @@ const fieldEncryption = function (schema, options) {
if (!data) {
return next;
}
// ! For the post-hook for .find and .findOne data is the first argument,
// ! therefore checking for an object in the first argument resolves the
// ! data.
if (typeof next === "object") {
return next;
}
return data;
}

Expand All @@ -147,6 +159,13 @@ const fieldEncryption = function (schema, options) {
}
}

function decryptArrayFields(data, fields, secret) {
// ! looping through the array of data (multiple docs)
for (var obj of data) {
decryptFields(obj, fields, secret);
}
}

function decryptFields(obj, fields, secret) {
for (const field of fields) {
const encryptedFieldName = encryptedFieldNamePrefix + field;
Expand Down Expand Up @@ -249,6 +268,39 @@ const fieldEncryption = function (schema, options) {
}
});

schema.post('find', function (_next, _data) {
const next = getCompatitibleNextFunc(_next, _data);
const data = getCompatibleData(_next, _data);
// ! checking if the request has lean()
if (this._mongooseOptions.lean) {
try {
// ! Data is being returned as an array. We need to loop through them.
decryptArrayFields(data, fieldsToEncrypt, secret());
next();
} catch (err) {
next(err);
}
} else {
next();
}
})

schema.post('findOne', function (_next, _data) {
const next = getCompatitibleNextFunc(_next, _data);
const data = getCompatibleData(_next, _data);
// ! checking if the request has lean()
if (this._mongooseOptions.lean) {
try {
decryptFields(data, fieldsToEncrypt, secret());
next();
} catch (err) {
next(err);
}
} else {
next();
}
})

schema.pre("findOneAndUpdate", updateHook);

schema.pre("update", updateHook);
Expand Down