move utility functions to their own file

This commit is contained in:
Kamal Bennani 2018-10-08 22:19:31 +02:00
parent ce534cf568
commit 4d3d4c8d55
No known key found for this signature in database
GPG Key ID: 4513063CDB1A1C25
2 changed files with 15 additions and 16 deletions

View File

@ -17,6 +17,8 @@ const { models: utilsModels } = require('strapi-utils');
// Local helpers. // Local helpers.
const utils = require('./utils/'); const utils = require('./utils/');
const _utils = utils();
const relations = require('./relations'); const relations = require('./relations');
/** /**
@ -524,23 +526,11 @@ module.exports = function (strapi) {
postProcessValue: (value) => { postProcessValue: (value) => {
if (_.isArray(value)) { if (_.isArray(value)) {
return value.map(valueToId); return value.map(_utils.valueToId);
} }
return valueToId(value); return _utils.valueToId(value);
} }
}, relations); }, relations);
return hook; return hook;
}; };
const valueToId = value => {
return isMongoId(value)
? mongoose.Types.ObjectId(value)
: value;
};
const isMongoId = (value) => {
const hexadecimal = /^[0-9A-F]+$/i;
return hexadecimal.test(value) && value.length === 24;
};

View File

@ -46,7 +46,16 @@ module.exports = (mongoose = new Mongoose()) => {
default: default:
} }
}, },
isObjectId: v => mongoose.Types.ObjectId.isValid(v), valueToId: value => {
toObjectId: v => mongoose.Types.ObjectId(v), return this.isMongoId(value)
? mongoose.Types.ObjectId(value)
: value;
},
isMongoId: (value) => {
// Here we don't use mongoose.Types.ObjectId.isValid method because it's a weird check,
// it returns for instance true for any integer value ¯\_(ツ)_/¯
const hexadecimal = /^[0-9A-F]+$/i;
return hexadecimal.test(value) && value.length === 24;
}
}; };
}; };