express-mongo-sanitize icon indicating copy to clipboard operation
express-mongo-sanitize copied to clipboard

Using a `replaceWith` function fails in some cases

Open hogpilot opened this issue 4 years ago • 1 comments

Providing a function for the replaceWith option only works if the function (when converted to a string) does not contain a "." character. This is due to the regex test here:

  if(!(TEST_REGEX.test(options.replaceWith))) {
    replaceWith = options.replaceWith;
  }

Recommend allowing any function for replaceWith by changing that block to:

  if(typeof options.replaceWith === 'function' || !(TEST_REGEX.test(options.replaceWith))) {
    replaceWith = options.replaceWith;
  }

By doing this, users can be more specific with their replace value, e.g.:

mongoSanitize({ replaceWith: (match) => {
  switch (match) {
    case '$':
      return '_dollar_';
    case '.': // this line currently triggers the `TEST_REGEX.test(options.replaceWith)`
      return '_dot_';
    default:
      return '_';
  }
} })

hogpilot avatar May 11 '21 15:05 hogpilot

Sorry for the delay in responding. This is a great idea - if you could make this change and include tests, I'd be happy to merge in.

fiznool avatar Jan 14 '22 10:01 fiznool