vat-validator
Version:
53 lines (50 loc) • 2.22 kB
JavaScript
var soap = require('soap');
var path = require('path');
var errors = require('./errors.js');
var config = require('./config.js');
exports.checkVatNumber = function(vatNumber, countryCode, callback) {
if (isFunction(countryCode)) {
callback = countryCode;
countryCode = config.webservice.default_country_code;
}
if (!countryCode)
countryCode = config.webservice.default_country_code;
soap.createClient(path.join(__dirname, config.webservice.wsdl), function(err, client) {
if (err)
return callback(err);
var checkVatData = {
countryCode: countryCode,
vatNumber: vatNumber
};
client.checkVat(checkVatData, function(err, result) {
if (err) {
if (err.checkNestedProperties('root', 'Envelope', 'Body', 'Fault', 'faultstring') && errors.ERROR_MSG[err.root.Envelope.Body.Fault.faultstring])
err.message = errors.ERROR_MSG[err.root.Envelope.Body.Fault.faultstring];
return callback(err);
}
result.validDesc = result.valid ? 'VALIDA' : 'NON VALIDA';
callback(undefined, result);
});
});
};
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
/* Aggiunge un extension method al prototype per controllare in modo recursivo l'esistenza delle proprietà specificate
L'aggancio del metodo è eseguito tramite defineProperty che aggiunge il metodo ad una enum, come definito dallo standard in ECMAScript 5 */
Object.defineProperty(Object.prototype, 'checkNestedProperties', {
value: function() {
/* Questa sintassi è un grado di generare un array di lunghezza pari al numero di parametri passati alla funzione, nel quale ogni elemento è un parametro */
var args = Array.prototype.slice.call(arguments, 0);
var obj = this;
for (var i = 0; i < args.length; i++) {
if (!obj || !obj.hasOwnProperty(args[i])) {
return false;
}
obj = obj[args[i]];
}
return true;
},
enumerable: false,
});