UNPKG

diffusion

Version:

Diffusion JavaScript client

98 lines (78 loc) 3.09 kB
var AbstractRecordModel = require('./abstract-record-model'); var FieldImpl = require('data/record/schema/field-impl'); function validateModel(schema, model) { var modelSize = model.length; var lastRecord = schema.lastRecord(); var lastIndex = lastRecord.index; var lastMax = lastRecord.max; if (lastMax !== -1 && modelSize > lastIndex + lastMax) { throw new Error("Too many occurrences of record '" + lastRecord.name + "'"); } if (modelSize < lastIndex + lastRecord.min) { throw new Error("Too few record occurrences"); } var schemaRecords = schema.records(); for (var r = 0; r < schemaRecords.length; ++r) { var schemaRecord = schemaRecords[r]; var startIndex = schemaRecord.index; var min = schemaRecord.min; for (var i = startIndex; i < startIndex + min; ++i) { validateRecord(schemaRecord, i - startIndex, model[i]); } // Process variable records to the end if (schemaRecord.isVariable) { for (var j = startIndex + min; j < modelSize; ++j) { var index = j - startIndex; validateRecord(schemaRecord, index, model[j]); } } } } function validateRecord(schemaRecord, recordIndex, record) { var recordSize = record.length; var lastField = schemaRecord.lastField(); var lastMax = lastField.max; var lastIndex = lastField.index; if (lastMax !== -1 && recordSize > lastIndex + lastMax) { throw new Error( "Too many occurrences of field '" + schemaRecord.name + "(" + recordIndex + ")." + lastField.name + "'"); } if (recordSize < lastIndex + lastField.min) { throw new Error("Too few field occurrences in record '" + schemaRecord.name + "(" + recordIndex + ")'"); } var fields = schemaRecord.fields(); for (var i = 0; i < fields.length; ++i) { var schemaField = fields[i]; var startIndex = schemaField.index; var min = schemaField.min; for (var j = startIndex; j < startIndex + min; ++j) { validateField(schemaRecord, recordIndex, schemaField, j - startIndex, record[j]); } if (schemaField.isVariable) { for (var k = startIndex + min; k < recordSize; k++) { var index = k - startIndex; validateField(schemaRecord, recordIndex, schemaField, index, record[k]); } } } } function validateField(schemaRecord, recordIndex, schemaField, index, value) { try { FieldImpl.normalise(schemaField, value); } catch (e) { throw new Error( "Invalid value for field '" + schemaRecord.name + "(" + recordIndex + ")." + schemaField.name + "(" + index + ")"); } } module.exports = function RecordModelImpl(constructor, schema, model, validate) { AbstractRecordModel.call(this, constructor, schema); if (validate) { validateModel(schema, model); } this.model = function() { return model; }; };