Skip to content

Commit

Permalink
Fill in default field values when cloning records.
Browse files Browse the repository at this point in the history
  • Loading branch information
mtth committed Dec 16, 2015
1 parent 1d5d14c commit 98eb097
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
7 changes: 6 additions & 1 deletion lib/schemas.js
Original file line number Diff line number Diff line change
Expand Up @@ -1720,7 +1720,12 @@ RecordType.prototype._copy = function (val, opts) {
var i, l, field, value;
for (i = 0, l = this._fields.length; i < l; i++) {
field = this._fields[i];
value = field._type._copy(val[field._name], opts);
value = val[field._name];
if (value === undefined && field.hasOwnProperty('getDefault')) {
value = field.getDefault();
} else {
value = field._type._copy(val[field._name], opts);
}
if (hook) {
value = hook(field, value, this);
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "avsc",
"version": "3.1.1",
"version": "3.1.2",
"description": "Blazing fast serialization",
"homepage": "https://github.com/mtth/avsc",
"keywords": [
Expand Down
41 changes: 41 additions & 0 deletions test/test_schemas.js
Original file line number Diff line number Diff line change
Expand Up @@ -1500,6 +1500,22 @@ suite('types', function () {
assert.equal(t.getSchema(true), '"earth.Person"');
});

test('fromString', function () {
var t = createType({
type: 'record',
name: 'Person',
fields: [
{name: 'age', type: 'int'},
{name: 'name', type: 'string', 'default': 'UNKNOWN'}
]
});
assert.deepEqual(
t.fromString('{"age": 23}'),
{age: 23, name: 'UNKNOWN'}
);
assert.throws(function () { t.fromString('{}'); });
});

test('toString record', function () {
var T = createType({
type: 'record',
Expand Down Expand Up @@ -1527,6 +1543,31 @@ suite('types', function () {
assert.deepEqual(c.$clone(), c);
});

test('clone field default', function () {
var t = createType({
type: 'record',
name: 'Person',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string', 'default': 'UNKNOWN'},
{name: 'age', type: ['null', 'int'], 'default': null},
]
});
assert.deepEqual(
t.clone({id: 1, name: 'Ann'}),
{id: 1, name: 'Ann', age: null}
);
assert.deepEqual(
t.clone({id: 1, name: 'Ann', age: {'int': 21}}),
{id: 1, name: 'Ann', age: {'int': 21}}
);
assert.deepEqual(
t.clone({id: 1, name: 'Ann', age: 21}, {wrapUnions: true}),
{id: 1, name: 'Ann', age: {'int': 21}}
);
assert.throws(function () { t.clone({}); });
});

test('clone field hook', function () {
var t = createType({
type: 'record',
Expand Down

0 comments on commit 98eb097

Please sign in to comment.