From 4d3d4c8d552f7b709ceb58f99b6cd3b80ce976de Mon Sep 17 00:00:00 2001 From: Kamal Bennani Date: Mon, 8 Oct 2018 22:19:31 +0200 Subject: [PATCH] move utility functions to their own file --- packages/strapi-hook-mongoose/lib/index.js | 18 ++++-------------- .../strapi-hook-mongoose/lib/utils/index.js | 13 +++++++++++-- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/packages/strapi-hook-mongoose/lib/index.js b/packages/strapi-hook-mongoose/lib/index.js index 3364a4026d..cdfdc16569 100644 --- a/packages/strapi-hook-mongoose/lib/index.js +++ b/packages/strapi-hook-mongoose/lib/index.js @@ -17,6 +17,8 @@ const { models: utilsModels } = require('strapi-utils'); // Local helpers. const utils = require('./utils/'); +const _utils = utils(); + const relations = require('./relations'); /** @@ -524,23 +526,11 @@ module.exports = function (strapi) { postProcessValue: (value) => { if (_.isArray(value)) { - return value.map(valueToId); + return value.map(_utils.valueToId); } - return valueToId(value); + return _utils.valueToId(value); } }, relations); 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; -}; diff --git a/packages/strapi-hook-mongoose/lib/utils/index.js b/packages/strapi-hook-mongoose/lib/utils/index.js index 94b198b2fc..ac267c9a97 100644 --- a/packages/strapi-hook-mongoose/lib/utils/index.js +++ b/packages/strapi-hook-mongoose/lib/utils/index.js @@ -46,7 +46,16 @@ module.exports = (mongoose = new Mongoose()) => { default: } }, - isObjectId: v => mongoose.Types.ObjectId.isValid(v), - toObjectId: v => mongoose.Types.ObjectId(v), + valueToId: value => { + 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; + } }; };