Skip to content

Commit 0fdd797

Browse files
common: support checking custom types
1 parent 17dae9b commit 0fdd797

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

packages/common/src/util.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -599,3 +599,29 @@ function createLimiter(makeRequestFn, options) {
599599
}
600600

601601
util.createLimiter = createLimiter;
602+
603+
function isCustomType(unknown, module) {
604+
function getConstructorName(obj) {
605+
return obj.constructor && obj.constructor.name.toLowerCase();
606+
}
607+
608+
var moduleNameParts = module.split('/');
609+
610+
var parentModuleName = moduleNameParts[0] && moduleNameParts[0].toLowerCase();
611+
var subModuleName = moduleNameParts[1] && moduleNameParts[1].toLowerCase();
612+
613+
if (subModuleName && getConstructorName(unknown) !== subModuleName) {
614+
return false;
615+
}
616+
617+
var walkingModule = unknown;
618+
while (walkingModule.parent && (walkingModule = walkingModule.parent)) {
619+
if (getConstructorName(walkingModule) === parentModuleName) {
620+
return true;
621+
}
622+
}
623+
624+
return false;
625+
}
626+
627+
util.isCustomType = isCustomType;

packages/common/test/util.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1370,4 +1370,30 @@ describe('common/util', function() {
13701370
});
13711371
});
13721372
});
1373+
1374+
describe('isCustomType', function() {
1375+
function PubSub() {}
1376+
1377+
function MiddleLayer() {
1378+
this.parent = new PubSub();
1379+
}
1380+
1381+
function Subscription() {
1382+
this.parent = new MiddleLayer();
1383+
}
1384+
1385+
var subscription = new Subscription();
1386+
1387+
it('should match a custom type by constructor names', function() {
1388+
assert(util.isCustomType(subscription, 'pubsub'));
1389+
assert(util.isCustomType(subscription, 'pubsub/subscription'));
1390+
1391+
assert(util.isCustomType(subscription, 'middlelayer'));
1392+
assert(util.isCustomType(subscription, 'middlelayer/subscription'));
1393+
});
1394+
1395+
it('should support any casing', function() {
1396+
assert(util.isCustomType(subscription, 'PubSub/Subscription'));
1397+
});
1398+
});
13731399
});

0 commit comments

Comments
 (0)