All files / helpers/sequelize hooks.js

97.05% Statements 33/34
47.36% Branches 18/38
100% Functions 16/16
96.96% Lines 32/33

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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78          14x           1251x 25x 9x 93x 8x               1251x 8x 8x 86x           1272x     2x 2x 2x 2x 4x             7x 7x 7x 7x         4x 4x 4x 3x         140000x 8x 8x 8x         140002x 10x 10x 10x        
/* eslint-disable no-control-regex */
/* eslint-disable no-empty */
// HOOKS
 
export function sanitizeToUtf8(input) {
  return input
    .replace(/[\u0000-\u001F\u007F-\u009F]/g, '')
    .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u{10000}-\u{10FFFF}]/gu, '');
}
 
// -- trim => Se for string remove espaços laterais e caracteres invisíveis
export const trimObjectValues = (dataValues = {}, fields = []) => {
  if (fields.length) {
    fields.forEach((field) => {
      if (dataValues[field] && typeof dataValues[field] === 'string')
        dataValues[field] = ['labelZPL', 'labelDPL'].includes(field)
          ? dataValues[field].trim()
          : sanitizeToUtf8(dataValues[field].trim());
    });
  }
};
 
// -- stringToPrimitive => converter new String intancia para string primitiva
const stringToPrimitive = (dataValues = {}, fields = []) => {
  Eif (fields.length) {
    fields.forEach((field) => {
      Iif (dataValues[field] && dataValues[field] instanceof String)
        dataValues[field] = dataValues[field].toString();
    });
  }
};
 
export const getHooks = () => ({
  beforeBulkCreate:
    (types = [], fields = []) =>
    (instances, options) => {
      try {
        Eif (types.includes('trim')) {
          for (const instance of instances) {
            trimObjectValues(instance.dataValues, fields.trim);
          }
        }
      } catch (e) {}
    },
  beforeCreate:
    (types = [], fields = []) =>
    (instance, options) => {
      try {
        Eif (types.includes('trim'))
          trimObjectValues(instance.dataValues, fields.trim);
      } catch (e) {}
    },
  beforeUpdate:
    (types = [], fields = []) =>
    (instance, options) => {
      try {
        if (types.includes('trim'))
          trimObjectValues(instance.dataValues, fields.trim);
      } catch (e) {}
    },
  beforeValidate:
    (types = [], fields = []) =>
    (instance, options) => {
      try {
        Eif (types.includes('stringToPrimitive'))
          stringToPrimitive(instance.dataValues, fields.stringToPrimitive);
      } catch (e) {}
    },
  afterValidate:
    (types = [], fields = []) =>
    (instance, options) => {
      try {
        Eif (types.includes('trim'))
          trimObjectValues(instance.dataValues, fields.trim);
      } catch (e) {}
    },
});