Skip to content

Commit

Permalink
Add type toJSON implementation
Browse files Browse the repository at this point in the history
The default behavior exposes internal data structures.
  • Loading branch information
mtth committed Jan 29, 2021
1 parent a735f0e commit 30a831a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
4 changes: 4 additions & 0 deletions packages/types/lib/types.js
Expand Up @@ -603,6 +603,10 @@ Type.prototype.schema = function (opts) {
});
};

Type.prototype.toJSON = function () {
return this.schema({exportAttrs: true});
};

Type.prototype.toString = function () {
return f('<%s>', getClassName(this.typeName));
};
Expand Down
2 changes: 1 addition & 1 deletion packages/types/package.json
@@ -1,6 +1,6 @@
{
"name": "@avro/types",
"version": "1.0.22",
"version": "1.0.23",
"description": "Avro serialization",
"homepage": "https://github.com/mtth/avsc",
"keywords": [
Expand Down
26 changes: 23 additions & 3 deletions packages/types/test/test-types.js
Expand Up @@ -1875,6 +1875,27 @@ suite('types', function () {
assert.equal(t.schema({noDeref: true}), 'earth.Person');
});

test('toJSON', function () {
var s = {
type: 'record',
name: 'earth.Person',
doc: 'Hi!',
aliases: ['earth.Human'],
fields: [
{name: 'friends', type: {type: 'array', items: 'string'}},
{
name: 'age',
aliases: ['years'],
type: 'int',
'default': 0,
order: 'descending'
}
]
};
var t = Type.forSchema(s)
assert.deepEqual(JSON.parse(JSON.stringify(t)), s);
});

test('schema recursive schema', function () {
var t = Type.forSchema({
type: 'record',
Expand Down Expand Up @@ -3304,7 +3325,7 @@ suite('types', function () {
});
});

suite('fromJSON', function () {
suite('JSON decode', function () {

test('int', function () {
var t = Type.forSchema('int');
Expand Down Expand Up @@ -3333,12 +3354,11 @@ suite('types', function () {

});

suite('toJSON', function () {
suite('JSON encode', function () {

test('int', function () {
var t = Type.forSchema('int');
assert.equal(t.jsonEncode(2), 2);
assert.throws(function () { t.toJSON('a'); });
});

});
Expand Down

0 comments on commit 30a831a

Please sign in to comment.