Skip to content

Commit

Permalink
fix: allow named types in unions
Browse files Browse the repository at this point in the history
  • Loading branch information
joscha committed Sep 11, 2024
1 parent 626ab67 commit 3d9efd5
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions lib/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ class Type {
this.name = undefined;
this.aliases = undefined;
this.doc = (schema && schema.doc) ? '' + schema.doc : undefined;
this.opts = Object.assign({}, opts);

if (schema) {
// This is a complex (i.e. non-primitive) type.
Expand Down Expand Up @@ -351,7 +352,7 @@ class Type {
// Group types by category, similar to the logic for unwrapped unions.
let bucketized = {};
expanded.forEach((type) => {
let bucket = getTypeBucket(type);
let bucket = getTypeBucket(type, true);
let bucketTypes = bucketized[bucket];
if (!bucketTypes) {
bucketized[bucket] = bucketTypes = [];
Expand Down Expand Up @@ -1258,7 +1259,7 @@ class UnwrappedUnionType extends UnionType {
}

_getIndex (val) {
let index = this._bucketIndices[getValueBucket(val)];
let index = this._bucketIndices[getValueBucket(val, this.opts.namespace)];
if (this._dynamicBranches) {
// Slower path, we must run the value through all branches.
index = this._getBranchIndex(val, index);
Expand Down Expand Up @@ -3027,8 +3028,9 @@ function maybeQualify(name, ns) {
* Get a type's bucket when included inside an unwrapped union.
*
* @param type {Type} Any type.
* @param isExpanded {Boolean} Whether the union is expanded - if yes, we don't use the name to determine the bucket, as the parent type is already in the right bucket.
*/
function getTypeBucket(type) {
function getTypeBucket(type, isExpanded) {
let typeName = type.typeName;
switch (typeName) {
case 'double':
Expand All @@ -3045,7 +3047,11 @@ function getTypeBucket(type) {
case 'error':
return 'object';
case 'record':
return type.name ? maybeQualify(type.name, type.namespace) : 'object';
if (isExpanded || !type.name) {
return 'object';
} else {
return maybeQualify(type.name, type.namespace)
}
default:
return typeName;
}
Expand All @@ -3055,8 +3061,9 @@ function getTypeBucket(type) {
* Infer a value's bucket (see unwrapped unions for more details).
*
* @param val {...} Any value.
* @param namespace {String} Optional namespace.
*/
function getValueBucket(val) {
function getValueBucket(val, namespace) {
if (val === null) {
return 'null';
}
Expand All @@ -3067,6 +3074,12 @@ function getValueBucket(val) {
return 'array';
} else if (Buffer.isBuffer(val)) {
return 'buffer';
} else if(typeof val.constructor !== 'undefined' && val.constructor.name) {
const isBuiltin = Object.values(module.exports.builtins).some(b => val instanceof b);
if (isBuiltin || val.constructor === Object) {
return bucket;
}
return maybeQualify(val.constructor.name, namespace);
}
}
return bucket;
Expand Down

0 comments on commit 3d9efd5

Please sign in to comment.