All files / src/validators schema.js

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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 4301x 1x   1x   1x   9x     46x 46x 27x 27x       27x 27x     27x 27x     27x     46x     58x     58x 58x     58x 20x     20x       58x         9x 9x 4x     4x     5x 5x     5x 5x     5x               9x 16x 7x     7x           9x 3x       3x 5x     5x             4x 4x       4x       4x       4x 8x                 8x                     4x 1x     1x             3x 3x     3x 6x             6x                               4x 8x 4x       4x                   4x 1x             1x 1x     1x                     9x       9x 9x 4x 4x     4x     4x       5x     5x             2x     2x     2x     2x     2x           9x 9x       9x       9x       9x 58x     9x   9x 2x     2x 4x       9x 1x       1x 9x       9x       9x       9x 1x     1x 2x           128x     128x     128x     128x 1x       128x     128x       1x       40319x 16x     40303x 40349x 40349x 3x       40300x     41345x 41345x 41345x 41345x 41345x   41345x 41345x 41335x       41345x 108x 1x       1x 107x 31x 62x   76x 66x       41345x       121967x   121967x 120326x   1641x 1641x           42x 1x   41x       42x     42x     42x       58x 8x   1x   7x   50x         1x  
const _ = require('lodash');
const util = require('util');
 
const datatypes = require('./datatypes');
 
const schemer = {
  validate_table_name(tableName) {
    return (typeof tableName === 'string' && /^[a-zA-Z]+[a-zA-Z0-9_]*/.test(tableName));
  },
  has_field(modelSchema, fieldName) {
    const optionFieldNames = [];
    if (modelSchema.options) {
      Eif (modelSchema.options.timestamps) {
        const timestampOptions = {
          createdAt: modelSchema.options.timestamps.createdAt || 'createdAt',
          updatedAt: modelSchema.options.timestamps.updatedAt || 'updatedAt',
        };
        optionFieldNames.push(timestampOptions.createdAt);
        optionFieldNames.push(timestampOptions.updatedAt);
      }
 
      Eif (modelSchema.options.versions) {
        const versionOptions = {
          key: modelSchema.options.versions.key || '__v',
        };
        optionFieldNames.push(versionOptions.key);
      }
    }
    return _.has(modelSchema.fields, fieldName) || optionFieldNames.includes(fieldName);
  },
  validate_field(modelSchema, fieldObject, fieldName) {
    Iif (!fieldObject) {
      throw (new Error(util.format('Schema field "%s" is not properly defined', fieldName)));
    }
    const fieldtype = this.get_field_type(modelSchema, fieldName);
    Iif (!_.has(datatypes, fieldtype)) {
      throw (new Error(util.format('Invalid field type "%s" for field: %s', fieldtype, fieldName)));
    }
    if (['map', 'list', 'set', 'frozen'].includes(fieldtype)) {
      Iif (!fieldObject.typeDef) {
        throw (new Error(util.format('Missing typeDef for field type "%s" on field: %s', fieldtype, fieldName)));
      }
      Iif (typeof fieldObject.typeDef !== 'string') {
        throw (new Error(util.format('Invalid typeDef for field type "%s" on field: %s', fieldtype, fieldName)));
      }
    }
    Iif (!(this.is_field_default_value_valid(modelSchema, fieldName))) {
      throw (new Error(util.format('Invalid default value for field: %s(%s)', fieldName, fieldtype)));
    }
  },
 
  validate_primary_key(modelSchema) {
    if (typeof (modelSchema.key[0]) === 'string') {
      Iif (!this.has_field(modelSchema, modelSchema.key[0])) {
        throw (new Error('Partition Key must also be a valid field name'));
      }
      Iif (modelSchema.fields[modelSchema.key[0]] && modelSchema.fields[modelSchema.key[0]].virtual) {
        throw (new Error("Partition Key must also be a db field name, can't be a virtual field name"));
      }
    } else Eif (_.isArray(modelSchema.key[0])) {
      Iif (modelSchema.key[0].length === 0) {
        throw (new Error("Partition Key array can't be empty"));
      }
      modelSchema.key[0].forEach((partitionKeyField) => {
        Iif ((typeof (partitionKeyField) !== 'string') || !this.has_field(modelSchema, partitionKeyField)) {
          throw (new Error('Partition Key array must contain only valid field names'));
        }
        Iif (modelSchema.fields[partitionKeyField] && modelSchema.fields[partitionKeyField].virtual) {
          throw (new Error("Partition Key array must contain only db field names, can't contain virtual field names"));
        }
      });
    } else {
      throw (new Error('Partition Key must be a field name string, or array of field names'));
    }
 
    modelSchema.key.forEach((primaryKeyField, primaryKeyIndex) => {
      if (primaryKeyIndex > 0) {
        Iif ((typeof (primaryKeyField) !== 'string') || !this.has_field(modelSchema, primaryKeyField)) {
          throw (new Error('Clustering Keys must be valid field names'));
        }
        Iif (modelSchema.fields[primaryKeyField] && modelSchema.fields[primaryKeyField].virtual) {
          throw (new Error("Clustering Keys must be db field names, can't be virtual field names"));
        }
      }
    });
 
    if (modelSchema.clustering_order) {
      Iif (!_.isPlainObject(modelSchema.clustering_order)) {
        throw (new Error('clustering_order must be an object of clustering_key attributes'));
      }
 
      _.forEach(modelSchema.clustering_order, (clusteringOrder, clusteringFieldName) => {
        Iif (!['asc', 'desc'].includes(clusteringOrder.toLowerCase())) {
          throw (new Error('clustering_order attribute values can only be ASC or DESC'));
        }
        Iif (modelSchema.key.indexOf(clusteringFieldName) < 1) {
          throw (new Error('clustering_order field attributes must be clustering keys only'));
        }
      });
    }
  },
 
  validate_materialized_view(modelSchema, materializedViewObject, materializedViewName) {
    Iif (!_.isPlainObject(materializedViewObject)) {
      throw (new Error(util.format('attribute "%s" under materialized_views must be an object', materializedViewName)));
    }
 
    Iif (!materializedViewObject.select || !materializedViewObject.key) {
      throw (new Error(util.format('materialized_view "%s" must have "select" and "key" attributes', materializedViewName)));
    }
 
    Iif (!_.isArray(materializedViewObject.select) || !_.isArray(materializedViewObject.key)) {
      throw (new Error(util.format('"select" and "key" attributes must be an array under attribute %s of materialized_views', materializedViewName)));
    }
 
    materializedViewObject.select.forEach((materializedViewSelectField) => {
      Iif ((typeof (materializedViewSelectField) !== 'string')
            || !(this.has_field(modelSchema, materializedViewSelectField)
            || materializedViewSelectField === '*')) {
        throw (new Error(util.format(
          'the select attribute under materialized_view %s must be an array of field name strings or ["*"]',
          materializedViewName,
        )));
      }
 
      Iif (modelSchema.fields[materializedViewSelectField]
          && modelSchema.fields[materializedViewSelectField].virtual) {
        throw (new Error(util.format(
          'the select attribute under %s of materialized_views must be an array of db field names, ' +
          'cannot contain any virtual field name',
          materializedViewName,
        )));
      }
    });
 
    // validate materialized_view primary key
    if (typeof (materializedViewObject.key[0]) === 'string') {
      Iif (!this.has_field(modelSchema, materializedViewObject.key[0])) {
        throw (new Error(util.format('materialized_view %s: partition key string must match a valid field name', materializedViewName)));
      }
      Iif (modelSchema.fields[materializedViewObject.key[0]]
        && modelSchema.fields[materializedViewObject.key[0]].virtual) {
        throw (new Error(util.format(
          'materialized_view %s: partition key must match a db field name, cannot be a virtual field name',
          materializedViewName,
        )));
      }
    } else Eif (_.isArray(materializedViewObject.key[0])) {
      Iif (materializedViewObject.key[0].length === 0) {
        throw (new Error(util.format('materialized_view %s: partition key array cannot be empty', materializedViewName)));
      }
      materializedViewObject.key[0].forEach((materializedViewPartitionKeyField) => {
        Iif ((typeof (materializedViewPartitionKeyField) !== 'string')
            || !this.has_field(modelSchema, materializedViewPartitionKeyField)) {
          throw (new Error(util.format(
            'materialized_view %s: partition key array must contain only valid field names',
            materializedViewName,
          )));
        }
        Iif (modelSchema.fields[materializedViewPartitionKeyField]
          && modelSchema.fields[materializedViewPartitionKeyField].virtual) {
          throw (new Error(util.format(
            'materialized_view %s: partition key array must contain only db field names, ' +
            'cannot contain virtual field names',
            materializedViewName,
          )));
        }
      });
    } else {
      throw (new Error(util.format(
        'materialized_view %s: partition key must be a field name string, or array of field names',
        materializedViewName,
      )));
    }
 
    materializedViewObject.key.forEach((materializedViewPrimaryKeyField, materializedViewPrimaryKeyIndex) => {
      if (materializedViewPrimaryKeyIndex > 0) {
        Iif ((typeof (materializedViewPrimaryKeyField) !== 'string')
            || !this.has_field(modelSchema, materializedViewPrimaryKeyField)) {
          throw (new Error(util.format('materialized_view %s: clustering keys must be valid field names', materializedViewName)));
        }
        Iif (modelSchema.fields[materializedViewPrimaryKeyField]
          && modelSchema.fields[materializedViewPrimaryKeyField].virtual) {
          throw (new Error(util.format(
            'materialized_view %s: clustering keys must be db field names, cannot contain virtual fields',
            materializedViewName,
          )));
        }
      }
    });
 
    if (materializedViewObject.clustering_order) {
      Iif (!_.isPlainObject(materializedViewObject.clustering_order)) {
        throw (new Error(util.format(
          'materialized_view %s: clustering_order must be an object of clustering_key attributes',
          materializedViewName,
        )));
      }
 
      _.forEach(materializedViewObject.clustering_order, (mvClusteringOrder, mvlusteringFieldName) => {
        Iif (!['asc', 'desc'].includes(mvClusteringOrder.toLowerCase())) {
          throw (new Error(util.format('materialized_view %s: clustering_order attribute values can only be ASC or DESC', materializedViewName)));
        }
        Iif (materializedViewObject.key.indexOf(mvlusteringFieldName) < 1) {
          throw (new Error(util.format(
            'materialized_view %s: clustering_order field attributes must be clustering keys only',
            materializedViewName,
          )));
        }
      });
    }
  },
 
  validate_index(modelSchema, indexDef) {
    Iif (typeof indexDef !== 'string') {
      throw (new Error('indexes must be an array of strings'));
    }
 
    const indexNameList = indexDef.replace(/["\s]/g, '').split(/[()]/g);
    if (indexNameList.length > 1) {
      indexNameList[0] = indexNameList[0].toLowerCase();
      Iif (!['entries', 'keys', 'values', 'full'].includes(indexNameList[0])) {
        throw (new Error(util.format('index "%s" is not defined properly', indexDef)));
      }
      Iif (!this.has_field(modelSchema, indexNameList[1])) {
        throw (new Error(util.format('"%s" is not a valid field name, indexes must be defined on field names', indexNameList[1])));
      }
      Iif (modelSchema.fields[indexNameList[1]] && modelSchema.fields[indexNameList[1]].virtual) {
        throw (new Error("indexes must be an array of db field names, can't contain virtual fields"));
      }
    } else {
      Iif (!this.has_field(modelSchema, indexNameList[0])) {
        throw (new Error(util.format('"%s" is not a valid field, indexes must be defined on field names', indexNameList[0])));
      }
      Iif (modelSchema.fields[indexNameList[0]] && modelSchema.fields[indexNameList[0]].virtual) {
        throw (new Error("indexes must be an array of db field names, can't contain virtual fields"));
      }
    }
  },
 
  validate_custom_index(modelSchema, customIndex) {
    Iif (!_.isPlainObject(customIndex)) {
      throw (new Error('custom_index must be an object with proper indexing attributes'));
    }
    Iif ((typeof (customIndex.on) !== 'string') || !this.has_field(modelSchema, customIndex.on)) {
      throw (new Error("custom_index must have an 'on' attribute with string value and value must be a valid field name"));
    }
    Iif (modelSchema.fields[customIndex.on] && modelSchema.fields[customIndex.on].virtual) {
      throw (new Error("custom_index 'on' attribute must be a db field name, can't contain virtual fields"));
    }
    Iif (typeof (customIndex.using) !== 'string') {
      throw (new Error("custom_index must have a 'using' attribute with string value"));
    }
    Iif (!_.isPlainObject(customIndex.options)) {
      throw (new Error('custom_index must have an "options" attribute and it must be an object, ' +
        'pass blank {} object if no options are required'));
    }
  },
 
  validate_model_schema(modelSchema) {
    Iif (!modelSchema) {
      throw (new Error('A schema must be specified'));
    }
 
    Iif (!_.isPlainObject(modelSchema.fields) || Object.keys(modelSchema.fields).length === 0) {
      throw (new Error('Schema must contain a non-empty "fields" map object'));
    }
 
    Iif (!modelSchema.key || !_.isArray(modelSchema.key)) {
      throw (new Error('Schema must contain "key" in the form: [ [partitionkey1, ...], clusteringkey1, ...]'));
    }
 
    _.forEach(modelSchema.fields, (fieldObject, fieldName) => {
      this.validate_field(modelSchema, fieldObject, fieldName);
    });
 
    this.validate_primary_key(modelSchema);
 
    if (modelSchema.materialized_views) {
      Iif (!_.isPlainObject(modelSchema.materialized_views)) {
        throw (new Error('materialized_views must be an object with view names as attributes'));
      }
      _.forEach(modelSchema.materialized_views, (materializedViewObject, materializedViewName) => {
        this.validate_materialized_view(modelSchema, materializedViewObject, materializedViewName);
      });
    }
 
    if (modelSchema.indexes) {
      Iif (!_.isArray(modelSchema.indexes)) {
        throw (new Error('indexes must be an array of field name strings'));
      }
 
      modelSchema.indexes.forEach((indexDef) => {
        this.validate_index(modelSchema, indexDef);
      });
    }
 
    Iif (modelSchema.custom_index && modelSchema.custom_indexes) {
      throw (new Error('both custom_index and custom_indexes are defined in schema, only one of them should be defined'));
    }
 
    Iif (modelSchema.custom_index) {
      this.validate_custom_index(modelSchema, modelSchema.custom_index);
    }
 
    if (modelSchema.custom_indexes) {
      Iif (!_.isArray(modelSchema.custom_indexes)) {
        throw (new Error('custom_indexes must be an array with objects with proper indexing attributes'));
      }
      modelSchema.custom_indexes.forEach((customIndex) => {
        this.validate_custom_index(modelSchema, customIndex);
      });
    }
  },
 
  format_validation_rule(rule, fieldname) {
    Iif (!_.isPlainObject(rule)) {
      throw (new Error(util.format('Validation rule for "%s" must be a function or an object', fieldname)));
    }
    Iif (typeof rule.validator !== 'function') {
      throw (new Error(util.format('Rule validator for "%s" must be a valid function', fieldname)));
    }
    Iif (!rule.message) {
      rule.message = this.get_generic_validation_message;
    }
    if (typeof rule.message === 'string') {
      rule.message = function f1(message) {
        return util.format(message);
      }.bind(null, rule.message);
    }
    Iif (typeof rule.message !== 'function') {
      throw (new Error(util.format('Invalid validator message for "%s", must be string or a function', fieldname)));
    }
    return rule;
  },
 
  get_generic_validation_message(value, propName, fieldtype) {
    return util.format('Invalid Value: "%s" for Field: %s (Type: %s)', value, propName, fieldtype);
  },
 
  get_validation_message(validators, value) {
    if (value == null || (_.isPlainObject(value) && value.$db_function)) {
      return true;
    }
 
    for (let v = 0; v < validators.length; v++) {
      Eif (typeof validators[v].validator === 'function') {
        if (!validators[v].validator(value)) {
          return validators[v].message;
        }
      }
    }
    return true;
  },
 
  get_validators(modelSchema, fieldname) {
    const validators = [];
    const fieldtype = this.get_field_type(modelSchema, fieldname);
    const typeFieldValidator = datatypes.generic_type_validator(fieldtype);
    const field = modelSchema.fields[fieldname];
 
    Eif (typeFieldValidator) {
      if (!(field.rule && field.rule.type_validation === false)) {
        validators.push(typeFieldValidator);
      }
    }
 
    if (typeof field.rule !== 'undefined') {
      if (typeof field.rule === 'function') {
        field.rule = {
          validator: field.rule,
          message: this.get_generic_validation_message,
        };
        validators.push(field.rule);
      } else if (Array.isArray(field.rule.validators)) {
        field.rule.validators.forEach((fieldrule) => {
          validators.push(this.format_validation_rule(fieldrule, fieldname));
        });
      } else if (field.rule.validator) {
        validators.push(this.format_validation_rule(field.rule, fieldname));
      }
    }
 
    return validators;
  },
 
  get_field_type(modelSchema, fieldName) {
    const fieldObject = modelSchema.fields[fieldName];
 
    if (typeof fieldObject === 'string') {
      return fieldObject;
    }
    Eif (_.isPlainObject(fieldObject)) {
      return fieldObject.type;
    }
    throw (new Error(`Type of field "${fieldName}" not defined properly`));
  },
 
  is_required_field(modelSchema, fieldName) {
    if (modelSchema.fields[fieldName].rule && modelSchema.fields[fieldName].rule.required) {
      return true;
    }
    return false;
  },
 
  is_primary_key_field(modelSchema, fieldName) {
    Iif (modelSchema.key.includes(fieldName)) {
      return true;
    }
    Iif (modelSchema.key[0] instanceof Array && modelSchema.key[0].includes(fieldName)) {
      return true;
    }
    return false;
  },
 
  is_field_default_value_valid(modelSchema, fieldName) {
    if (_.isPlainObject(modelSchema.fields[fieldName]) && modelSchema.fields[fieldName].default) {
      if (_.isPlainObject(modelSchema.fields[fieldName].default)
          && !(modelSchema.fields[fieldName].default.$db_function)) {
        return ['map', 'list', 'set', 'frozen'].includes(modelSchema.fields[fieldName].type);
      }
      return true;
    }
    return true;
  },
 
};
 
module.exports = schemer;