All files / utils validateDescription.js

100% Statements 12/12
100% Branches 12/12
100% Functions 1/1
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 418x                     150x   12x   12x 15x   14x 14x 4x                               8x     8x  
const { MAX_DESCRIPTION_NEWLINES } = require('./constants')
 
/**
 * Validates that an entity description does not exceed the maximum number
 * of line breaks. The description can be a plain string or a multilingual
 * object ({ en: '...', fr: '...' }).
 *
 * @param {string|Object} description - The description from the request body
 * @returns {{ valid: boolean, errorResponse?: object }}
 */
function validateDescription(description) {
  if (description === undefined || description === null) return { valid: true }
 
  const values = typeof description === 'string' ? [description] : Object.values(description)
 
  for (const value of values) {
    if (typeof value !== 'string') continue
 
    const newlineCount = (value.match(/\n/g) || []).length
    if (newlineCount > MAX_DESCRIPTION_NEWLINES) {
      return {
        valid: false,
        errorResponse: {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({
            error: `Description cannot contain more than ${MAX_DESCRIPTION_NEWLINES} line breaks`
          })
        }
      }
    }
  }
 
  return { valid: true }
}
 
module.exports = { validateDescription }