Add ducktyping Filter.isFilter method

This should make some headway in avoiding instanceof pitfalls when
dealing with Filter objects.

Fix mcavage/node-ldapjs#123
This commit is contained in:
Patrick Mooney 2014-06-23 18:09:56 -05:00
parent f3e376d40b
commit 00956eaae5
4 changed files with 20 additions and 4 deletions

View File

@ -40,7 +40,6 @@ var SearchReference = messages.SearchReference;
var SearchResponse = messages.SearchResponse;
var Parser = messages.Parser;
var Filter = filters.Filter;
var PresenceFilter = filters.PresenceFilter;
var ConnectionError = errors.ConnectionError;
@ -640,7 +639,7 @@ Client.prototype.search = function search(base, options, controls, callback) {
options.filter = filters.parseString(options.filter);
} else if (!options.filter) {
options.filter = new PresenceFilter({attribute: 'objectclass'});
} else if (!(options.filter instanceof Filter)) {
} else if (!filters.isFilter(options.filter)) {
throw new TypeError('options.filter (Filter) required');
}

View File

@ -44,6 +44,21 @@ function Filter(options) {
}
});
}
Filter.isFilter = function isFilter(filter) {
if (!filter || typeof (filter) !== 'object') {
return false;
}
// Do our best to duck-type it
if ((filter instanceof Filter) || (
typeof (filter.toBer) === 'functin' &&
typeof (filter.matches) === 'function' &&
typeof (filter._type) === 'number')) {
return true;
}
return false;
};
module.exports = Filter;

View File

@ -547,6 +547,8 @@ module.exports = {
return _parseString(filter);
},
isFilter: Filter.isFilter,
AndFilter: AndFilter,
ApproximateFilter: ApproximateFilter,
EqualityFilter: EqualityFilter,

View File

@ -13,7 +13,7 @@ var Protocol = require('../protocol');
function NotFilter(options) {
if (typeof (options) === 'object') {
if (!options.filter || !(options.filter instanceof Filter))
if (!options.filter || !Filter.isFilter(options.filter))
throw new TypeError('options.filter (Filter) required');
} else {
@ -37,7 +37,7 @@ module.exports = NotFilter;
NotFilter.prototype.addFilter = function (f) {
if (!(f instanceof Filter))
if (!Filter.isFilter(f))
throw new TypeError('filter (Filter) required');
this.filter = f;
};