Skip to content

Commit

Permalink
Support optional fields using IDL question mark syntax (#446)
Browse files Browse the repository at this point in the history
  • Loading branch information
yehonatanz authored Jan 27, 2024
1 parent 9330777 commit a605733
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/specs.js
Original file line number Diff line number Diff line change
Expand Up @@ -427,11 +427,15 @@ class Reader {
if (javadoc !== undefined && schema.doc === undefined) {
schema.doc = javadoc;
}
const isOptional = tk.next({id: 'operator', val: '?', silent: true});
this._readAnnotations(schema);
schema.name = tk.next({id: 'name'}).val;
if (tk.next({val: '=', silent: true})) {
schema['default'] = tk.next({id: 'json'}).val;
}
if (isOptional) {
schema.type = 'default' in schema && schema.default !== null ? [schema.type, 'null'] : ['null', schema.type];
}
return schema;
}

Expand Down
24 changes: 24 additions & 0 deletions test/test_specs.js
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,30 @@ suite('specs', () => {
);
});

test('optional field no default value', () => {
const usingQuestionMark = readSchema('record { int? optionalInt; }');
const usingUnion = readSchema('record { union{null,int} optionalInt; }');
assert.deepEqual(usingQuestionMark, usingUnion);
});

test('optional field null default value', () => {
const usingQuestionMark = readSchema('record { int? optionalInt = null; }');
const usingUnion = readSchema('record { union{null,int} optionalInt = null; }');
assert.deepEqual(usingQuestionMark, usingUnion);
});

test('optional field non-null default value', () => {
const usingQuestionMark = readSchema('record { int? optionalInt = 0; }');
const usingUnion = readSchema('record { union{int,null} optionalInt = 0; }');
assert.deepEqual(usingQuestionMark, usingUnion);
});

test('optional field with annotations', () => {
const usingQuestionMark = readSchema('record { int? @order("ascending") optionalInt = 0; }');
const usingUnion = readSchema('record { union{int,null} @order("ascending") optionalInt = 0; }');
assert.deepEqual(usingQuestionMark, usingUnion);
});

});

suite('readProtocol', () => {
Expand Down

0 comments on commit a605733

Please sign in to comment.