Skip to content

Commit 77c83a1

Browse files
stephenpluspluscallmehiphop
authored andcommitted
common: support checking custom types (#1529)
* common: support checking custom types * test parent module matching * simplification
1 parent 868f0f0 commit 77c83a1

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-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+
do {
619+
if (getConstructorName(walkingModule) === parentModuleName) {
620+
return true;
621+
}
622+
} while ((walkingModule = walkingModule.parent));
623+
624+
return false;
625+
}
626+
627+
util.isCustomType = isCustomType;

packages/common/test/util.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1370,4 +1370,35 @@ 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 pubsub = new PubSub();
1386+
var subscription = new Subscription();
1387+
1388+
it('should match a Service type by constructor names', function() {
1389+
assert(util.isCustomType(pubsub, 'pubsub'));
1390+
});
1391+
1392+
it('should match a ServiceObject type by constructor names', function() {
1393+
assert(util.isCustomType(subscription, 'pubsub'));
1394+
assert(util.isCustomType(subscription, 'pubsub/subscription'));
1395+
1396+
assert(util.isCustomType(subscription, 'middlelayer'));
1397+
assert(util.isCustomType(subscription, 'middlelayer/subscription'));
1398+
});
1399+
1400+
it('should support any casing', function() {
1401+
assert(util.isCustomType(subscription, 'PubSub/Subscription'));
1402+
});
1403+
});
13731404
});

0 commit comments

Comments
 (0)