Skip to content

Commit

Permalink
add mongoose 4-5 compatibility
Browse files Browse the repository at this point in the history
.
  • Loading branch information
devdoomari3 committed Aug 23, 2018
1 parent 677279e commit 7fbb504
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions lib/mongoose-field-encryption.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ const fieldEncryption = function(schema, options) {
const fieldsToEncrypt = options.fields || [];
const secret = options.secret;

// for mongoose 4/5 compatibility
const defaultNext = function defaultNext(err) {
if (err) { throw err }
}
function getCompatitibleNextFunc(next) {
if (typeof next !== 'function') {
return defaultNext;
}
return next;
}

// add marker fields to schema
for (let field of fieldsToEncrypt) {
const encryptedFieldName = encryptedFieldNamePrefix + field;
Expand All @@ -47,7 +58,7 @@ const fieldEncryption = function(schema, options) {
const fieldValue = obj[field];

if (!obj[encryptedFieldName] && fieldValue) {
if (typeof fieldValue === 'string') { // handle strings separately to maintain searchability
if (typeof fieldValue === 'string') { // handle strings separately to maintain searchability
const value = encrypt(fieldValue, secret);
obj[field] = value;
} else {
Expand All @@ -73,7 +84,7 @@ const fieldEncryption = function(schema, options) {
obj[encryptedFieldName] = false;
obj[encryptedFieldData] = '';

} else if (obj[encryptedFieldName]) { // handle strings separately to maintain searchability
} else if (obj[encryptedFieldName]) { // handle strings separately to maintain searchability
const encryptedValue = obj[field];

obj[field] = decrypt(encryptedValue, secret);
Expand All @@ -82,7 +93,8 @@ const fieldEncryption = function(schema, options) {
}
};

schema.pre('init', function(next, data) {
schema.pre('init', function(_next, data) {
const next = getCompatitibleNextFunc(_next)
try {
decryptFields(data, fieldsToEncrypt, secret);
next();
Expand All @@ -91,7 +103,8 @@ const fieldEncryption = function(schema, options) {
}
});

schema.pre('save', function(next) {
schema.pre('save', function(_next) {
const next = getCompatitibleNextFunc(_next)
try {
encryptFields(this, fieldsToEncrypt, secret);
next();
Expand All @@ -100,8 +113,8 @@ const fieldEncryption = function(schema, options) {
}
});

schema.pre('update', function(next) {

schema.pre('update', function(_next) {
const next = getCompatitibleNextFunc(_next)
for (let field of fieldsToEncrypt) {

let encryptedFieldName = encryptedFieldNamePrefix + field;
Expand Down

0 comments on commit 7fbb504

Please sign in to comment.