All files / utils validateFieldNames.js

86.66% Statements 13/15
86.66% Branches 13/15
100% Functions 3/3
90.9% Lines 10/11

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 41 42 43 44 45 46                        23x   23x 29x 5x                               18x       29x 27x 2x 3x         2x  
/**
 * Validates that every field in an entity's fields array has a non-empty name.
 *
 * Field names can be a plain string or a multilingual object ({ en: '...', fr: '...' }).
 * A field is considered unnamed when:
 *  - field.name is absent, null, or an empty string, OR
 *  - field.name is an object with no entry that has a non-blank value.
 *
 * @param {Array} fields - The entity fields array from the request body
 * @returns {{ valid: boolean, errorResponse?: object }}
 */
function validateFieldNames(fields) {
  Iif (!Array.isArray(fields)) return { valid: true }
 
  for (const field of fields) {
    if (!hasName(field)) {
      return {
        valid: false,
        errorResponse: {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({
            error: 'Each field must have a non-empty name'
          })
        }
      }
    }
  }
 
  return { valid: true }
}
 
function hasName(field) {
  if (!field || field.name === undefined || field.name === null) return false
  if (typeof field.name === 'string') return field.name.trim().length > 0
  Eif (typeof field.name === 'object') {
    return Object.values(field.name).some((v) => typeof v === 'string' && v.trim().length > 0)
  }
  return false
}
 
module.exports = { validateFieldNames }