diffusion
Version:
Diffusion JavaScript client
93 lines (70 loc) • 2.1 kB
JavaScript
var FieldImpl = require('data/record/schema/field-impl');
module.exports = function RecordImpl(name, min, max, index, _fields) {
this.name = name;
this.min = min;
this.max = max;
this.index = index;
this.isVariable = min !== max;
var fields = {};
_fields.forEach(function(field) {
fields[field.name] = field;
});
this.fields = function() {
return _fields;
};
this.getFields = function() {
return [].concat(_fields);
};
this.getField = function(fieldName) {
var field = fields[fieldName];
if (field) {
return field;
}
throw new Error("Record '" + name + "' has no field named '" + fieldName + "'");
};
this.lastField = function() {
return _fields[_fields.length - 1];
};
this.createModel = function() {
var fields = [];
_fields.forEach(function(field) {
for (var i = 0; i < field.min; ++i) {
fields.push(FieldImpl.modelValue(field));
}
});
return fields;
};
this.getAbsoluteIndex = function(_index) {
if (_index < 0 || max !== -1 && _index > max - 1) {
throw new Error("Invalid index '" + _index + "' for record '" + name + "'");
}
return index + _index;
};
this.toString = function() {
var ret = "Record [Name=" + name;
if (min === max) {
ret += ", Occurs=" + min;
} else {
ret += ", Min=" + min + ", Max=";
if (max === -1) {
ret += "Unlimited";
} else {
ret += max;
}
}
ret +=", Fields=" + _fields + "]";
return ret;
};
};
module.exports.toJSON = function(record) {
var sanitised = {};
record.fields().forEach(function(field) {
sanitised[field.name] = FieldImpl.toJSON(field);
}, {});
return {
fields : record.fields().map(FieldImpl.toJSON),
name : record.name,
min : record.min,
max : record.max
};
};