Skip to content

Commit

Permalink
Add Type.forValue tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mtth committed May 7, 2019
1 parent 02dd68a commit dd23066
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
13 changes: 12 additions & 1 deletion packages/types/lib/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -1803,7 +1803,7 @@ function RecordType(schema, opts, scope) {
// Force creation of the options object in case we need to register this
// record's name.
opts = opts || {};
scope = scope || Scope.forOptions(opts);
scope = scope ? scope.clone() : Scope.forOptions(opts);

// Save the namespace to restore it as we leave this record's scope.
if (schema.namespace !== undefined) {
Expand Down Expand Up @@ -2527,6 +2527,13 @@ function Resolver(writerType, readerType) {

Resolver.prototype._peek = Type.prototype._peek;

/**
* Type creation scope.
*
* Currently it holds the current namespace and the path to the type being
* generated (useful in type hooks when generating record names for
* `Type.forValue` for example).
*/
function Scope(namespace, path) {
this.namespace = namespace;
this.path = path || [];
Expand All @@ -2536,6 +2543,10 @@ Scope.forOptions = function (opts) {
return new Scope(opts ? opts.namespace : undefined);
};

Scope.prototype.clone = function () {
return new Scope(this.namespace, this.path);
};

Scope.prototype.child = function (step) {
return new Scope(this.namespace, this.path.concat('' + step));
};
Expand Down
2 changes: 1 addition & 1 deletion packages/types/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@avro/types",
"version": "1.0.1",
"version": "1.0.2",
"description": "Avro serialization",
"homepage": "https://github.com/mtth/avsc",
"keywords": [
Expand Down
28 changes: 28 additions & 0 deletions packages/types/test/test-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -3721,6 +3721,34 @@ suite('types', function () {
}
}
});

test('type hook array', function () {
var i = 1;
var t = infer([{foo: 2}, {foo: 3}], {typeHook: hook}).itemsType;
assert.equal(t.name, 'Foo3');
assert.equal(t.field('foo').type.typeName, 'int');
function hook(schema) {
if (schema.type !== 'record') {
return;
}
schema.name = 'Foo' + (i++);
}
});

test('type hook nested array', function () {
var i = 1;
var outer = infer([[{foo: 2}], [{foo: 3}]], {typeHook: hook});
var inner = outer.itemsType.itemsType;
assert.equal(inner.name, 'Foo3');
assert.equal(inner.field('foo').type.typeName, 'int');

function hook(schema) {
if (schema.type !== 'record') {
return;
}
schema.name = 'Foo' + (i++);
}
});
});
});

Expand Down

0 comments on commit dd23066

Please sign in to comment.