From fe05d46615c36a43f4f64ea8f6e677ced0add884 Mon Sep 17 00:00:00 2001 From: Rodrigo Teixeira Andreotti Date: Tue, 20 Feb 2024 21:31:32 -0300 Subject: [PATCH 01/10] Add postmon as new provider --- dist/cep-promise-browser.js | 406 ++++++++---------- dist/cep-promise-browser.min.js | 2 +- dist/cep-promise.js | 340 ++++++--------- dist/cep-promise.min.js | 2 +- src/services/index.js | 3 + src/services/postmon.js | 66 +++ test/unit/cep-promise-providers.spec.js | 63 +++ .../unit/fixtures/postmon-05010000-found.json | 13 + .../fixtures/postmon-cep-99999999-error.json | 0 9 files changed, 460 insertions(+), 435 deletions(-) create mode 100644 src/services/postmon.js create mode 100644 test/unit/fixtures/postmon-05010000-found.json create mode 100644 test/unit/fixtures/postmon-cep-99999999-error.json diff --git a/dist/cep-promise-browser.js b/dist/cep-promise-browser.js index e9ec1c63..0e3a72f6 100644 --- a/dist/cep-promise-browser.js +++ b/dist/cep-promise-browser.js @@ -4,33 +4,73 @@ (global = global || self, global.cep = factory()); }(this, (function () { 'use strict'; - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; + function _callSuper(t, o, e) { + return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); + } + function _construct(t, e, r) { + if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); + var o = [null]; + o.push.apply(o, e); + var p = new (t.bind.apply(t, o))(); + return r && _setPrototypeOf(p, r.prototype), p; + } + function _isNativeReflectConstruct() { + try { + var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + } catch (t) {} + return (_isNativeReflectConstruct = function () { + return !!t; + })(); + } + function _toPrimitive(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r || "default"); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); } - - return _typeof(obj); + return ("string" === r ? String : Number)(t); + } + function _toPropertyKey(t) { + var i = _toPrimitive(t, "string"); + return "symbol" == typeof i ? i : String(i); } + function _typeof(o) { + "@babel/helpers - typeof"; + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, _typeof(o); + } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; + } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } - subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, @@ -38,79 +78,45 @@ configurable: true } }); + Object.defineProperty(subClass, "prototype", { + writable: false + }); if (superClass) _setPrototypeOf(subClass, superClass); } - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; - return _setPrototypeOf(o, p); } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - + function _isNativeFunction(fn) { try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; + return Function.toString.call(fn).indexOf("[native code]") !== -1; } catch (e) { - return false; - } - } - - function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; + return typeof fn === "function"; } - - return _construct.apply(null, arguments); } - - function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; - _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; - if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } - if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); - _cache.set(Class, Wrapper); } - function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } - Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, @@ -121,57 +127,31 @@ }); return _setPrototypeOf(Wrapper, Class); }; - return _wrapNativeSuper(Class); } - function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } - return self; } - function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); } - return _assertThisInitialized(self); } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - - return _possibleConstructorReturn(this, result); - }; - } - function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } - function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); @@ -180,29 +160,21 @@ if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - return arr2; } - function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - function _createForOfIteratorHelper(o, allowArrayLike) { - var it; - - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; - var F = function () {}; - return { s: F, n: function () { @@ -220,16 +192,14 @@ f: F }; } - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - var normalCompletion = true, - didErr = false, - err; + didErr = false, + err; return { s: function () { - it = o[Symbol.iterator](); + it = it.call(o); }, n: function () { var step = it.next(); @@ -252,103 +222,85 @@ var CepPromiseError = /*#__PURE__*/function (_Error) { _inherits(CepPromiseError, _Error); - - var _super = _createSuper(CepPromiseError); - function CepPromiseError() { var _this; - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - message = _ref.message, - type = _ref.type, - errors = _ref.errors; - + message = _ref.message, + type = _ref.type, + errors = _ref.errors; _classCallCheck(this, CepPromiseError); - - _this = _super.call(this); + _this = _callSuper(this, CepPromiseError); _this.name = 'CepPromiseError'; _this.message = message; _this.type = type; _this.errors = errors; return _this; } - - return CepPromiseError; + return _createClass(CepPromiseError); }( /*#__PURE__*/_wrapNativeSuper(Error)); function fetch (e, n) { return n = n || {}, new Promise(function (t, r) { var s = new XMLHttpRequest(), - o = [], - u = [], - i = {}, - a = function a() { - return { - ok: 2 == (s.status / 100 | 0), - statusText: s.statusText, - status: s.status, - url: s.responseURL, - text: function text() { - return Promise.resolve(s.responseText); - }, - json: function json() { - return Promise.resolve(JSON.parse(s.responseText)); - }, - blob: function blob() { - return Promise.resolve(new Blob([s.response])); - }, - clone: a, - headers: { - keys: function keys() { - return o; + o = [], + u = [], + i = {}, + a = function a() { + return { + ok: 2 == (s.status / 100 | 0), + statusText: s.statusText, + status: s.status, + url: s.responseURL, + text: function text() { + return Promise.resolve(s.responseText); }, - entries: function entries() { - return u; + json: function json() { + return Promise.resolve(JSON.parse(s.responseText)); }, - get: function get(e) { - return i[e.toLowerCase()]; + blob: function blob() { + return Promise.resolve(new Blob([s.response])); }, - has: function has(e) { - return e.toLowerCase() in i; + clone: a, + headers: { + keys: function keys() { + return o; + }, + entries: function entries() { + return u; + }, + get: function get(e) { + return i[e.toLowerCase()]; + }, + has: function has(e) { + return e.toLowerCase() in i; + } } - } + }; }; - }; - for (var l in s.open(n.method || "get", e, !0), s.onload = function () { s.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, function (e, n, t) { o.push(n = n.toLowerCase()), u.push([n, t]), i[n] = i[n] ? i[n] + "," + t : t; }), t(a()); - }, s.onerror = r, s.withCredentials = "include" == n.credentials, n.headers) { - s.setRequestHeader(l, n.headers[l]); - } - + }, s.onerror = r, s.withCredentials = "include" == n.credentials, n.headers) s.setRequestHeader(l, n.headers[l]); s.send(n.body || null); }); } var ServiceError = /*#__PURE__*/function (_Error) { _inherits(ServiceError, _Error); - - var _super = _createSuper(ServiceError); - function ServiceError() { var _this; - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - message = _ref.message, - service = _ref.service; - + message = _ref.message, + service = _ref.service; _classCallCheck(this, ServiceError); - - _this = _super.call(this); + _this = _callSuper(this, ServiceError); _this.name = 'ServiceError'; _this.message = message; _this.service = service; return _this; } - - return ServiceError; + return _createClass(ServiceError); }( /*#__PURE__*/_wrapNativeSuper(Error)); function fetchCorreiosService(cepWithLeftPad, configurations) { @@ -364,28 +316,22 @@ }; return fetch(url, options).then(analyzeAndParseResponse)["catch"](throwApplicationError); } - function analyzeAndParseResponse(response) { if (response.ok) { return response.text().then(parseSuccessXML).then(extractValuesFromSuccessResponse); } - return response.text().then(parseAndextractErrorMessage).then(throwCorreiosError); } - function parseSuccessXML(xmlString) { try { var _xmlString$replace$ma; - var returnStatement = (_xmlString$replace$ma = xmlString.replace(/\r?\n|\r/g, '').match(/(.*)<\/return>/)[0]) !== null && _xmlString$replace$ma !== void 0 ? _xmlString$replace$ma : ''; var cleanReturnStatement = returnStatement.replace('', '').replace('', ''); var parsedReturnStatement = cleanReturnStatement.split(/'); - if (splittenExp.length > 1 && splittenExp[1].length) { result[splittenExp[0]] = splittenExp[1]; } - return result; }, {}); return parsedReturnStatement; @@ -393,11 +339,9 @@ throw new Error('Não foi possível interpretar o XML de resposta.'); } } - function parseAndextractErrorMessage(xmlString) { try { var _xmlString$match$; - var returnStatement = (_xmlString$match$ = xmlString.match(/(.*)<\/faultstring>/)[0]) !== null && _xmlString$match$ !== void 0 ? _xmlString$match$ : ''; var cleanReturnStatement = returnStatement.replace('', '').replace('', ''); return cleanReturnStatement; @@ -405,11 +349,9 @@ throw new Error('Não foi possível interpretar o XML de resposta.'); } } - function throwCorreiosError(translatedErrorMessage) { throw new Error(translatedErrorMessage); } - function extractValuesFromSuccessResponse(xmlObject) { return { cep: xmlObject.cep, @@ -420,17 +362,14 @@ service: 'correios' }; } - function throwApplicationError(error) { var serviceError = new ServiceError({ message: error.message, service: 'correios' }); - if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço dos Correios.'; } - throw serviceError; } @@ -449,17 +388,14 @@ }; return fetch(url, options).then(parseResponse).then(extractCepValuesFromResponse)["catch"](throwApplicationError$1); } - function parseResponse(response) { return response.json().then(function (result) { if (result.total === 0 || result.erro || result.dados[0].cep === "") { throw new Error('CEP não encontrado na base dos Correios.'); } - return result; }); } - function extractCepValuesFromResponse(response) { var firstCep = response.dados[0]; return { @@ -471,17 +407,14 @@ service: 'correios-alt' }; } - function throwApplicationError$1(error) { var serviceError = new ServiceError({ message: error.message, service: 'correios-alt' }); - if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço dos Correios Alt.'; } - throw serviceError; } @@ -495,30 +428,23 @@ }, timeout: configurations.timeout || 30000 }; - if (typeof window == 'undefined') { options.headers['user-agent'] = 'cep-promise'; } - return fetch(url, options).then(analyzeAndParseResponse$1).then(checkForViaCepError).then(extractCepValuesFromResponse$1)["catch"](throwApplicationError$2); } - function analyzeAndParseResponse$1(response) { if (response.ok) { return response.json(); } - throw Error('Erro ao se conectar com o serviço ViaCEP.'); } - function checkForViaCepError(responseObject) { if (responseObject.erro === true) { throw new Error('CEP não encontrado na base do ViaCEP.'); } - return responseObject; } - function extractCepValuesFromResponse$1(responseObject) { return { cep: responseObject.cep.replace('-', ''), @@ -529,17 +455,14 @@ service: 'viacep' }; } - function throwApplicationError$2(error) { var serviceError = new ServiceError({ message: error.message, service: 'viacep' }); - if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço ViaCEP.'; } - throw serviceError; } @@ -554,26 +477,70 @@ }, timeout: configurations.timeout || 30000 }; - return fetch(url, options).then(analyzeAndParseResponse$2).then(checkForWideNetError).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3); + if (typeof window == 'undefined') { + options.headers['user-agent'] = 'cep-promise'; + } + return fetch(url, options).then(analyzeAndParseResponse$2).then(checkForPostmanError).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3); } - function analyzeAndParseResponse$2(response) { if (response.ok) { return response.json(); } + throw Error('Erro ao se conectar com o serviço Postmon.'); + } + function checkForPostmanError(responseObject) { + if (!responseObject) { + throw new Error('CEP não encontrado na base do Postmon.'); + } + return responseObject; + } + function extractCepValuesFromResponse$2(responseObject) { + return { + cep: responseObject.cep.replace('-', ''), + state: responseObject.estado, + city: responseObject.cidade, + neighborhood: responseObject.bairro, + street: responseObject.logradouro, + service: 'postmon' + }; + } + function throwApplicationError$3(error) { + var serviceError = new ServiceError({ + message: error.message, + service: 'viacep' + }); + if (error.name === 'FetchError') { + serviceError.message = 'Erro ao se conectar com o serviço Postmon.'; + } + throw serviceError; + } + function fetchWideNetService(cepWithLeftPad, configurations) { + var cepWithDash = "".concat(cepWithLeftPad.slice(0, 5), "-").concat(cepWithLeftPad.slice(5)); + var url = "https://cdn.apicep.com/file/apicep/".concat(cepWithDash, ".json"); + var options = { + method: 'GET', + mode: 'cors', + headers: { + accept: 'application/json' + }, + timeout: configurations.timeout || 30000 + }; + return fetch(url, options).then(analyzeAndParseResponse$3).then(checkForWideNetError).then(extractCepValuesFromResponse$3)["catch"](throwApplicationError$4); + } + function analyzeAndParseResponse$3(response) { + if (response.ok) { + return response.json(); + } throw Error('Erro ao se conectar com o serviço WideNet.'); } - function checkForWideNetError(object) { if (object.ok === false || object.status !== 200) { throw new Error('CEP não encontrado na base do WideNet.'); } - return object; } - - function extractCepValuesFromResponse$2(object) { + function extractCepValuesFromResponse$3(object) { return { cep: object.code.replace('-', ''), state: object.state, @@ -583,17 +550,14 @@ service: 'widenet' }; } - - function throwApplicationError$3(error) { + function throwApplicationError$4(error) { var serviceError = new ServiceError({ message: error.message, service: 'widenet' }); - if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço WideNet.'; } - throw serviceError; } @@ -607,18 +571,15 @@ }, timeout: configurations.timeout || 30000 }; - return fetch(url, options).then(parseResponse$1).then(extractCepValuesFromResponse$3)["catch"](throwApplicationError$4); + return fetch(url, options).then(parseResponse$1).then(extractCepValuesFromResponse$4)["catch"](throwApplicationError$5); } - function parseResponse$1(response) { if (response.ok === false || response.status !== 200) { throw new Error('CEP não encontrado na base do BrasilAPI.'); } - return response.json(); } - - function extractCepValuesFromResponse$3(response) { + function extractCepValuesFromResponse$4(response) { return { cep: response.cep, state: response.state, @@ -628,36 +589,33 @@ service: 'brasilapi' }; } - - function throwApplicationError$4(error) { + function throwApplicationError$5(error) { var serviceError = new ServiceError({ message: error.message, service: 'brasilapi' }); - if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço BrasilAPI.'; } - throw serviceError; } function getAvailableServices() { var isBrowser = typeof window !== 'undefined'; - if (isBrowser) { return { viacep: fetchViaCepService, widenet: fetchWideNetService, + postmon: fetchViaCepService$1, brasilapi: fetchBrasilAPIService }; } - return { correios: fetchCorreiosService, 'correios-alt': fetchCorreiosAltAPIService, viacep: fetchViaCepService, widenet: fetchWideNetService, + postmon: fetchViaCepService$1, brasilapi: fetchBrasilAPIService }; } @@ -667,11 +625,9 @@ return Promise.resolve(promise).then(reject, resolve); }); }; - Promise.any = function (iterable) { return reverse(Promise.all(_toConsumableArray(iterable).map(reverse))); }; - var Promise$1 = Promise; var CEP_SIZE = 8; @@ -683,12 +639,10 @@ return cepRawValue; }).then(removeSpecialCharacters).then(validateInputLength).then(leftPadWithZeros).then(function (cepWithLeftPad) { return fetchCepFromServices(cepWithLeftPad, configurations); - })["catch"](handleServicesError)["catch"](throwApplicationError$5); + })["catch"](handleServicesError)["catch"](throwApplicationError$6); } - function validateProviders(providers) { var availableProviders = Object.keys(getAvailableServices()); - if (!Array.isArray(providers)) { throw new CepPromiseError({ message: 'Erro ao inicializar a instância do CepPromise.', @@ -699,14 +653,11 @@ }] }); } - var _iterator = _createForOfIteratorHelper(providers), - _step; - + _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var provider = _step.value; - if (!availableProviders.includes(provider)) { throw new CepPromiseError({ message: 'Erro ao inicializar a instância do CepPromise.', @@ -724,14 +675,11 @@ _iterator.f(); } } - function validateInputType(cepRawValue) { var cepTypeOf = _typeof(cepRawValue); - if (cepTypeOf === 'number' || cepTypeOf === 'string') { return cepRawValue; } - throw new CepPromiseError({ message: 'Erro ao inicializar a instância do CepPromise.', type: 'validation_error', @@ -741,20 +689,16 @@ }] }); } - function removeSpecialCharacters(cepRawValue) { return cepRawValue.toString().replace(/\D+/g, ''); } - function leftPadWithZeros(cepCleanValue) { return '0'.repeat(CEP_SIZE - cepCleanValue.length) + cepCleanValue; } - function validateInputLength(cepWithLeftPad) { if (cepWithLeftPad.length <= CEP_SIZE) { return cepWithLeftPad; } - throw new CepPromiseError({ message: "CEP deve conter exatamente ".concat(CEP_SIZE, " caracteres."), type: 'validation_error', @@ -764,21 +708,17 @@ }] }); } - function fetchCepFromServices(cepWithLeftPad, configurations) { var providersServices = getAvailableServices(); - if (configurations.providers.length === 0) { return Promise$1.any(Object.values(providersServices).map(function (provider) { return provider(cepWithLeftPad, configurations); })); } - return Promise$1.any(configurations.providers.map(function (provider) { return providersServices[provider](cepWithLeftPad, configurations); })); } - function handleServicesError(aggregatedErrors) { if (aggregatedErrors.length !== undefined) { throw new CepPromiseError({ @@ -787,14 +727,12 @@ errors: aggregatedErrors }); } - throw aggregatedErrors; } - - function throwApplicationError$5(_ref) { + function throwApplicationError$6(_ref) { var message = _ref.message, - type = _ref.type, - errors = _ref.errors; + type = _ref.type, + errors = _ref.errors; throw new CepPromiseError({ message: message, type: type, diff --git a/dist/cep-promise-browser.min.js b/dist/cep-promise-browser.min.js index 3a33d466..23604289 100644 --- a/dist/cep-promise-browser.min.js +++ b/dist/cep-promise-browser.min.js @@ -1 +1 @@ -!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e=e||self).cep=r()}(this,function(){"use strict";function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function a(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function e(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),r&&i(e,r)}function o(e){return(o=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function i(e,r){return(i=Object.setPrototypeOf||function(e,r){return e.__proto__=r,e})(e,r)}function c(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(e){return!1}}function s(e,r,t){return(s=c()?Reflect.construct:function(e,r,t){var n=[null];n.push.apply(n,r);var o=new(Function.bind.apply(e,n));return t&&i(o,t.prototype),o}).apply(null,arguments)}function r(e){var n="function"==typeof Map?new Map:void 0;return(r=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(e))return n.get(e);n.set(e,t)}function t(){return s(e,arguments,o(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),i(t,e)})(e)}function u(e,r){return!r||"object"!=typeof r&&"function"!=typeof r?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):r}function n(t){var n=c();return function(){var e,r=o(t);return u(this,n?(e=o(this).constructor,Reflect.construct(r,arguments,e)):r.apply(this,arguments))}}function p(e){return function(e){if(Array.isArray(e))return l(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||f(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function f(e,r){if(e){if("string"==typeof e)return l(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?l(e,r):void 0}}function l(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4}).then(y).catch(P)}function y(e){return e.ok?e.text().then(b).then(E):e.text().then(g).then(w)}function b(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function w(e){throw new Error(e)}function E(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function P(e){var r=new m({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}function C(e,r){return h("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",{method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(e,"&tipoCEP=ALL"),timeout:r.timeout||3e4}).then(S).then(j).catch(x)}function S(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep)throw new Error("CEP não encontrado na base dos Correios.");return e})}function j(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function x(e){var r=new m({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function O(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),n={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(n.headers["user-agent"]="cep-promise"),h(t,n).then(A).then(T).then(_).catch(R)}function A(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function T(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function _(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function R(e){var r=new m({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function F(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5));return h("https://cdn.apicep.com/file/apicep/".concat(t,".json"),{method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4}).then(L).then(k).then(N).catch(I)}function L(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function k(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function N(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function I(e){var r=new m({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function M(e,r){return h("https://brasilapi.com.br/api/cep/v1/".concat(e),{method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4}).then(B).then(z).catch(D)}function B(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function z(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function D(e){var r=new m({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function H(){return"undefined"!=typeof window?{viacep:O,widenet:F,brasilapi:M}:{correios:v,"correios-alt":C,viacep:O,widenet:F,brasilapi:M}}function U(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return U(Promise.all(p(e).map(U)))};var V=Promise,q=8;function G(e){var r=t(e);if("number"===r||"string"===r)return e;throw new d({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function W(e){return e.toString().replace(/\D+/g,"")}function X(e){return"0".repeat(q-e.length)+e}function J(e){if(e.length<=q)return e;throw new d({message:"CEP deve conter exatamente ".concat(q," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(q," caracteres."),service:"cep_validation"}]})}function $(e){if(void 0!==e.length)throw new d({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function K(e){var r=e.message,t=e.type,n=e.errors;throw new d({message:r,type:t,errors:n})}return function(e){var o=1=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,c=!0,a=!1;return{s:function(){t=e[Symbol.iterator]()},n:function(){var e=t.next();return c=e.done,e},e:function(e){a=!0,i=e},f:function(){try{c||null==t.return||t.return()}finally{if(a)throw i}}}}(e);try{for(n.s();!(t=n.n()).done;){var o=t.value;if(!r.includes(o))throw new d({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(o,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){n.e(e)}finally{n.f()}}(o.providers),e}).then(W).then(J).then(X).then(function(e){return r=e,t=o,n=H(),0!==t.providers.length?V.any(t.providers.map(function(e){return n[e](r,t)})):V.any(Object.values(n).map(function(e){return e(r,t)}));var r,t,n}).catch($).catch(K)}}); \ No newline at end of file +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e=e||self).cep=r()}(this,function(){"use strict";function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function a(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function e(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),r&&i(e,r)}function o(e){return(o=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function i(e,r){return(i=Object.setPrototypeOf||function(e,r){return e.__proto__=r,e})(e,r)}function c(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(e){return!1}}function s(e,r,t){return(s=c()?Reflect.construct:function(e,r,t){var n=[null];n.push.apply(n,r);var o=new(Function.bind.apply(e,n));return t&&i(o,t.prototype),o}).apply(null,arguments)}function r(e){var n="function"==typeof Map?new Map:void 0;return(r=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(e))return n.get(e);n.set(e,t)}function t(){return s(e,arguments,o(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),i(t,e)})(e)}function u(e,r){return!r||"object"!=typeof r&&"function"!=typeof r?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):r}function n(t){var n=c();return function(){var e,r=o(t);return u(this,n?(e=o(this).constructor,Reflect.construct(r,arguments,e)):r.apply(this,arguments))}}function p(e){return function(e){if(Array.isArray(e))return l(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||f(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function f(e,r){if(e){if("string"==typeof e)return l(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?l(e,r):void 0}}function l(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4}).then(y).catch(P)}function y(e){return e.ok?e.text().then(b).then(E):e.text().then(g).then(w)}function b(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function w(e){throw new Error(e)}function E(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function P(e){var r=new m({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}function C(e,r){return h("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",{method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(e,"&tipoCEP=ALL"),timeout:r.timeout||3e4}).then(S).then(j).catch(x)}function S(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep)throw new Error("CEP não encontrado na base dos Correios.");return e})}function j(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function x(e){var r=new m({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function O(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),n={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(n.headers["user-agent"]="cep-promise"),h(t,n).then(A).then(T).then(_).catch(R)}function A(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function T(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function _(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function R(e){var r=new m({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function F(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5));return h("https://cdn.apicep.com/file/apicep/".concat(t,".json"),{method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4}).then(L).then(k).then(N).catch(I)}function L(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function k(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function N(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function I(e){var r=new m({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function M(e,r){return h("https://brasilapi.com.br/api/cep/v1/".concat(e),{method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4}).then(B).then(z).catch(D)}function B(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function z(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function D(e){var r=new m({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function H(){return"undefined"!=typeof window?{viacep:O,widenet:F,brasilapi:M}:{correios:v,"correios-alt":C,viacep:O,widenet:F,brasilapi:M}}function U(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return U(Promise.all(p(e).map(U)))};var V=Promise,q=8;function G(e){var r=t(e);if("number"===r||"string"===r)return e;throw new d({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function W(e){return e.toString().replace(/\D+/g,"")}function X(e){return"0".repeat(q-e.length)+e}function J(e){if(e.length<=q)return e;throw new d({message:"CEP deve conter exatamente ".concat(q," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(q," caracteres."),service:"cep_validation"}]})}function $(e){if(void 0!==e.length)throw new d({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function K(e){var r=e.message,t=e.type,n=e.errors;throw new d({message:r,type:t,errors:n})}return function(e){var o=1=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,c=!0,a=!1;return{s:function(){t=e[Symbol.iterator]()},n:function(){var e=t.next();return c=e.done,e},e:function(e){a=!0,i=e},f:function(){try{c||null==t.return||t.return()}finally{if(a)throw i}}}}(e);try{for(n.s();!(t=n.n()).done;){var o=t.value;if(!r.includes(o))throw new d({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(o,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){n.e(e)}finally{n.f()}}(o.providers),e}).then(W).then(J).then(X).then(function(e){return r=e,t=o,n=H(),0!==t.providers.length?V.any(t.providers.map(function(e){return n[e](r,t)})):V.any(Object.values(n).map(function(e){return e(r,t)}));var r,t,n}).catch($).catch(K)}}); diff --git a/dist/cep-promise.js b/dist/cep-promise.js index b82e4e72..7ff6bce9 100644 --- a/dist/cep-promise.js +++ b/dist/cep-promise.js @@ -6,33 +6,73 @@ fetch = fetch && Object.prototype.hasOwnProperty.call(fetch, 'default') ? fetch['default'] : fetch; - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; + function _callSuper(t, o, e) { + return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); + } + function _construct(t, e, r) { + if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); + var o = [null]; + o.push.apply(o, e); + var p = new (t.bind.apply(t, o))(); + return r && _setPrototypeOf(p, r.prototype), p; + } + function _isNativeReflectConstruct() { + try { + var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + } catch (t) {} + return (_isNativeReflectConstruct = function () { + return !!t; + })(); + } + function _toPrimitive(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r || "default"); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); } - - return _typeof(obj); + return ("string" === r ? String : Number)(t); } + function _toPropertyKey(t) { + var i = _toPrimitive(t, "string"); + return "symbol" == typeof i ? i : String(i); + } + function _typeof(o) { + "@babel/helpers - typeof"; + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, _typeof(o); + } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; + } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } - subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, @@ -40,79 +80,45 @@ configurable: true } }); + Object.defineProperty(subClass, "prototype", { + writable: false + }); if (superClass) _setPrototypeOf(subClass, superClass); } - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; - return _setPrototypeOf(o, p); } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - + function _isNativeFunction(fn) { try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; + return Function.toString.call(fn).indexOf("[native code]") !== -1; } catch (e) { - return false; - } - } - - function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; + return typeof fn === "function"; } - - return _construct.apply(null, arguments); - } - - function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; } - function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; - _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; - if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } - if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); - _cache.set(Class, Wrapper); } - function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } - Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, @@ -123,57 +129,31 @@ }); return _setPrototypeOf(Wrapper, Class); }; - return _wrapNativeSuper(Class); } - function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } - return self; } - function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); } - return _assertThisInitialized(self); } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - - return _possibleConstructorReturn(this, result); - }; - } - function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } - function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); @@ -182,29 +162,21 @@ if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - return arr2; } - function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - function _createForOfIteratorHelper(o, allowArrayLike) { - var it; - - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; - var F = function () {}; - return { s: F, n: function () { @@ -222,16 +194,14 @@ f: F }; } - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - var normalCompletion = true, - didErr = false, - err; + didErr = false, + err; return { s: function () { - it = o[Symbol.iterator](); + it = it.call(o); }, n: function () { var step = it.next(); @@ -254,52 +224,38 @@ var CepPromiseError = /*#__PURE__*/function (_Error) { _inherits(CepPromiseError, _Error); - - var _super = _createSuper(CepPromiseError); - function CepPromiseError() { var _this; - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - message = _ref.message, - type = _ref.type, - errors = _ref.errors; - + message = _ref.message, + type = _ref.type, + errors = _ref.errors; _classCallCheck(this, CepPromiseError); - - _this = _super.call(this); + _this = _callSuper(this, CepPromiseError); _this.name = 'CepPromiseError'; _this.message = message; _this.type = type; _this.errors = errors; return _this; } - - return CepPromiseError; + return _createClass(CepPromiseError); }( /*#__PURE__*/_wrapNativeSuper(Error)); var ServiceError = /*#__PURE__*/function (_Error) { _inherits(ServiceError, _Error); - - var _super = _createSuper(ServiceError); - function ServiceError() { var _this; - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - message = _ref.message, - service = _ref.service; - + message = _ref.message, + service = _ref.service; _classCallCheck(this, ServiceError); - - _this = _super.call(this); + _this = _callSuper(this, ServiceError); _this.name = 'ServiceError'; _this.message = message; _this.service = service; return _this; } - - return ServiceError; + return _createClass(ServiceError); }( /*#__PURE__*/_wrapNativeSuper(Error)); function fetchCorreiosService(cepWithLeftPad, configurations) { @@ -315,28 +271,22 @@ }; return fetch(url, options).then(analyzeAndParseResponse)["catch"](throwApplicationError); } - function analyzeAndParseResponse(response) { if (response.ok) { return response.text().then(parseSuccessXML).then(extractValuesFromSuccessResponse); } - return response.text().then(parseAndextractErrorMessage).then(throwCorreiosError); } - function parseSuccessXML(xmlString) { try { var _xmlString$replace$ma; - var returnStatement = (_xmlString$replace$ma = xmlString.replace(/\r?\n|\r/g, '').match(/(.*)<\/return>/)[0]) !== null && _xmlString$replace$ma !== void 0 ? _xmlString$replace$ma : ''; var cleanReturnStatement = returnStatement.replace('', '').replace('', ''); var parsedReturnStatement = cleanReturnStatement.split(/'); - if (splittenExp.length > 1 && splittenExp[1].length) { result[splittenExp[0]] = splittenExp[1]; } - return result; }, {}); return parsedReturnStatement; @@ -344,11 +294,9 @@ throw new Error('Não foi possível interpretar o XML de resposta.'); } } - function parseAndextractErrorMessage(xmlString) { try { var _xmlString$match$; - var returnStatement = (_xmlString$match$ = xmlString.match(/(.*)<\/faultstring>/)[0]) !== null && _xmlString$match$ !== void 0 ? _xmlString$match$ : ''; var cleanReturnStatement = returnStatement.replace('', '').replace('', ''); return cleanReturnStatement; @@ -356,11 +304,9 @@ throw new Error('Não foi possível interpretar o XML de resposta.'); } } - function throwCorreiosError(translatedErrorMessage) { throw new Error(translatedErrorMessage); } - function extractValuesFromSuccessResponse(xmlObject) { return { cep: xmlObject.cep, @@ -371,17 +317,14 @@ service: 'correios' }; } - function throwApplicationError(error) { var serviceError = new ServiceError({ message: error.message, service: 'correios' }); - if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço dos Correios.'; } - throw serviceError; } @@ -400,17 +343,14 @@ }; return fetch(url, options).then(parseResponse).then(extractCepValuesFromResponse)["catch"](throwApplicationError$1); } - function parseResponse(response) { return response.json().then(function (result) { if (result.total === 0 || result.erro || result.dados[0].cep === "") { throw new Error('CEP não encontrado na base dos Correios.'); } - return result; }); } - function extractCepValuesFromResponse(response) { var firstCep = response.dados[0]; return { @@ -422,17 +362,14 @@ service: 'correios-alt' }; } - function throwApplicationError$1(error) { var serviceError = new ServiceError({ message: error.message, service: 'correios-alt' }); - if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço dos Correios Alt.'; } - throw serviceError; } @@ -446,30 +383,23 @@ }, timeout: configurations.timeout || 30000 }; - if (typeof window == 'undefined') { options.headers['user-agent'] = 'cep-promise'; } - return fetch(url, options).then(analyzeAndParseResponse$1).then(checkForViaCepError).then(extractCepValuesFromResponse$1)["catch"](throwApplicationError$2); } - function analyzeAndParseResponse$1(response) { if (response.ok) { return response.json(); } - throw Error('Erro ao se conectar com o serviço ViaCEP.'); } - function checkForViaCepError(responseObject) { if (responseObject.erro === true) { throw new Error('CEP não encontrado na base do ViaCEP.'); } - return responseObject; } - function extractCepValuesFromResponse$1(responseObject) { return { cep: responseObject.cep.replace('-', ''), @@ -480,17 +410,14 @@ service: 'viacep' }; } - function throwApplicationError$2(error) { var serviceError = new ServiceError({ message: error.message, service: 'viacep' }); - if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço ViaCEP.'; } - throw serviceError; } @@ -505,26 +432,70 @@ }, timeout: configurations.timeout || 30000 }; - return fetch(url, options).then(analyzeAndParseResponse$2).then(checkForWideNetError).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3); + if (typeof window == 'undefined') { + options.headers['user-agent'] = 'cep-promise'; + } + return fetch(url, options).then(analyzeAndParseResponse$2).then(checkForPostmanError).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3); } - function analyzeAndParseResponse$2(response) { if (response.ok) { return response.json(); } + throw Error('Erro ao se conectar com o serviço Postmon.'); + } + function checkForPostmanError(responseObject) { + if (!responseObject) { + throw new Error('CEP não encontrado na base do Postmon.'); + } + return responseObject; + } + function extractCepValuesFromResponse$2(responseObject) { + return { + cep: responseObject.cep.replace('-', ''), + state: responseObject.estado, + city: responseObject.cidade, + neighborhood: responseObject.bairro, + street: responseObject.logradouro, + service: 'postmon' + }; + } + function throwApplicationError$3(error) { + var serviceError = new ServiceError({ + message: error.message, + service: 'viacep' + }); + if (error.name === 'FetchError') { + serviceError.message = 'Erro ao se conectar com o serviço Postmon.'; + } + throw serviceError; + } + function fetchWideNetService(cepWithLeftPad, configurations) { + var cepWithDash = "".concat(cepWithLeftPad.slice(0, 5), "-").concat(cepWithLeftPad.slice(5)); + var url = "https://cdn.apicep.com/file/apicep/".concat(cepWithDash, ".json"); + var options = { + method: 'GET', + mode: 'cors', + headers: { + accept: 'application/json' + }, + timeout: configurations.timeout || 30000 + }; + return fetch(url, options).then(analyzeAndParseResponse$3).then(checkForWideNetError).then(extractCepValuesFromResponse$3)["catch"](throwApplicationError$4); + } + function analyzeAndParseResponse$3(response) { + if (response.ok) { + return response.json(); + } throw Error('Erro ao se conectar com o serviço WideNet.'); } - function checkForWideNetError(object) { if (object.ok === false || object.status !== 200) { throw new Error('CEP não encontrado na base do WideNet.'); } - return object; } - - function extractCepValuesFromResponse$2(object) { + function extractCepValuesFromResponse$3(object) { return { cep: object.code.replace('-', ''), state: object.state, @@ -534,17 +505,14 @@ service: 'widenet' }; } - - function throwApplicationError$3(error) { + function throwApplicationError$4(error) { var serviceError = new ServiceError({ message: error.message, service: 'widenet' }); - if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço WideNet.'; } - throw serviceError; } @@ -558,18 +526,15 @@ }, timeout: configurations.timeout || 30000 }; - return fetch(url, options).then(parseResponse$1).then(extractCepValuesFromResponse$3)["catch"](throwApplicationError$4); + return fetch(url, options).then(parseResponse$1).then(extractCepValuesFromResponse$4)["catch"](throwApplicationError$5); } - function parseResponse$1(response) { if (response.ok === false || response.status !== 200) { throw new Error('CEP não encontrado na base do BrasilAPI.'); } - return response.json(); } - - function extractCepValuesFromResponse$3(response) { + function extractCepValuesFromResponse$4(response) { return { cep: response.cep, state: response.state, @@ -579,36 +544,33 @@ service: 'brasilapi' }; } - - function throwApplicationError$4(error) { + function throwApplicationError$5(error) { var serviceError = new ServiceError({ message: error.message, service: 'brasilapi' }); - if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço BrasilAPI.'; } - throw serviceError; } function getAvailableServices() { var isBrowser = typeof window !== 'undefined'; - if (isBrowser) { return { viacep: fetchViaCepService, widenet: fetchWideNetService, + postmon: fetchViaCepService$1, brasilapi: fetchBrasilAPIService }; } - return { correios: fetchCorreiosService, 'correios-alt': fetchCorreiosAltAPIService, viacep: fetchViaCepService, widenet: fetchWideNetService, + postmon: fetchViaCepService$1, brasilapi: fetchBrasilAPIService }; } @@ -618,11 +580,9 @@ return Promise.resolve(promise).then(reject, resolve); }); }; - Promise.any = function (iterable) { return reverse(Promise.all(_toConsumableArray(iterable).map(reverse))); }; - var Promise$1 = Promise; var CEP_SIZE = 8; @@ -634,12 +594,10 @@ return cepRawValue; }).then(removeSpecialCharacters).then(validateInputLength).then(leftPadWithZeros).then(function (cepWithLeftPad) { return fetchCepFromServices(cepWithLeftPad, configurations); - })["catch"](handleServicesError)["catch"](throwApplicationError$5); + })["catch"](handleServicesError)["catch"](throwApplicationError$6); } - function validateProviders(providers) { var availableProviders = Object.keys(getAvailableServices()); - if (!Array.isArray(providers)) { throw new CepPromiseError({ message: 'Erro ao inicializar a instância do CepPromise.', @@ -650,14 +608,11 @@ }] }); } - var _iterator = _createForOfIteratorHelper(providers), - _step; - + _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var provider = _step.value; - if (!availableProviders.includes(provider)) { throw new CepPromiseError({ message: 'Erro ao inicializar a instância do CepPromise.', @@ -675,14 +630,11 @@ _iterator.f(); } } - function validateInputType(cepRawValue) { var cepTypeOf = _typeof(cepRawValue); - if (cepTypeOf === 'number' || cepTypeOf === 'string') { return cepRawValue; } - throw new CepPromiseError({ message: 'Erro ao inicializar a instância do CepPromise.', type: 'validation_error', @@ -692,20 +644,16 @@ }] }); } - function removeSpecialCharacters(cepRawValue) { return cepRawValue.toString().replace(/\D+/g, ''); } - function leftPadWithZeros(cepCleanValue) { return '0'.repeat(CEP_SIZE - cepCleanValue.length) + cepCleanValue; } - function validateInputLength(cepWithLeftPad) { if (cepWithLeftPad.length <= CEP_SIZE) { return cepWithLeftPad; } - throw new CepPromiseError({ message: "CEP deve conter exatamente ".concat(CEP_SIZE, " caracteres."), type: 'validation_error', @@ -715,21 +663,17 @@ }] }); } - function fetchCepFromServices(cepWithLeftPad, configurations) { var providersServices = getAvailableServices(); - if (configurations.providers.length === 0) { return Promise$1.any(Object.values(providersServices).map(function (provider) { return provider(cepWithLeftPad, configurations); })); } - return Promise$1.any(configurations.providers.map(function (provider) { return providersServices[provider](cepWithLeftPad, configurations); })); } - function handleServicesError(aggregatedErrors) { if (aggregatedErrors.length !== undefined) { throw new CepPromiseError({ @@ -738,14 +682,12 @@ errors: aggregatedErrors }); } - throw aggregatedErrors; } - - function throwApplicationError$5(_ref) { + function throwApplicationError$6(_ref) { var message = _ref.message, - type = _ref.type, - errors = _ref.errors; + type = _ref.type, + errors = _ref.errors; throw new CepPromiseError({ message: message, type: type, diff --git a/dist/cep-promise.min.js b/dist/cep-promise.min.js index 4a7d8a29..22c4c94f 100644 --- a/dist/cep-promise.min.js +++ b/dist/cep-promise.min.js @@ -1 +1 @@ -!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r(require("node-fetch")):"function"==typeof define&&define.amd?define(["node-fetch"],r):(e=e||self).cep=r(e.fetch)}(this,function(i){"use strict";function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function a(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function e(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),r&&c(e,r)}function n(e){return(n=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function c(e,r){return(c=Object.setPrototypeOf||function(e,r){return e.__proto__=r,e})(e,r)}function s(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(e){return!1}}function u(e,r,t){return(u=s()?Reflect.construct:function(e,r,t){var o=[null];o.push.apply(o,r);var n=new(Function.bind.apply(e,o));return t&&c(n,t.prototype),n}).apply(null,arguments)}function r(e){var o="function"==typeof Map?new Map:void 0;return(r=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==o){if(o.has(e))return o.get(e);o.set(e,t)}function t(){return u(e,arguments,n(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),c(t,e)})(e)}function p(e,r){return!r||"object"!=typeof r&&"function"!=typeof r?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):r}function o(t){var o=s();return function(){var e,r=n(t);return p(this,o?(e=n(this).constructor,Reflect.construct(r,arguments,e)):r.apply(this,arguments))}}function f(e){return function(e){if(Array.isArray(e))return d(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||l(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,r){if(e){if("string"==typeof e)return d(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?d(e,r):void 0}}function d(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,o=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4};return i("https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente",t).then(y).catch(P)}function y(e){return e.ok?e.text().then(b).then(E):e.text().then(g).then(w)}function b(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function w(e){throw new Error(e)}function E(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function P(e){var r=new m({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}function j(e,r){var t={method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(e,"&tipoCEP=ALL"),timeout:r.timeout||3e4};return i("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",t).then(C).then(S).catch(O)}function C(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep)throw new Error("CEP não encontrado na base dos Correios.");return e})}function S(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function O(e){var r=new m({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function x(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),i(t,o).then(A).then(_).then(T).catch(F)}function A(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function _(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function T(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function F(e){var r=new m({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function R(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5)),o="https://cdn.apicep.com/file/apicep/".concat(t,".json"),n={method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4};return i(o,n).then(I).then(N).then(k).catch(M)}function I(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function N(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function k(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function M(e){var r=new m({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function z(e,r){var t="https://brasilapi.com.br/api/cep/v1/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return i(t,o).then(B).then(D).catch(L)}function B(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function D(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function L(e){var r=new m({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function V(){return"undefined"!=typeof window?{viacep:x,widenet:R,brasilapi:z}:{correios:v,"correios-alt":j,viacep:x,widenet:R,brasilapi:z}}function G(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return G(Promise.all(f(e).map(G)))};var U=Promise,W=8;function q(e){var r=t(e);if("number"===r||"string"===r)return e;throw new h({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function X(e){return e.toString().replace(/\D+/g,"")}function H(e){return"0".repeat(W-e.length)+e}function J(e){if(e.length<=W)return e;throw new h({message:"CEP deve conter exatamente ".concat(W," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(W," caracteres."),service:"cep_validation"}]})}function $(e){if(void 0!==e.length)throw new h({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function K(e){var r=e.message,t=e.type,o=e.errors;throw new h({message:r,type:t,errors:o})}return function(e){var n=1=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,c=!0,a=!1;return{s:function(){t=e[Symbol.iterator]()},n:function(){var e=t.next();return c=e.done,e},e:function(e){a=!0,i=e},f:function(){try{c||null==t.return||t.return()}finally{if(a)throw i}}}}(e);try{for(o.s();!(t=o.n()).done;){var n=t.value;if(!r.includes(n))throw new h({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(n,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){o.e(e)}finally{o.f()}}(n.providers),e}).then(X).then(J).then(H).then(function(e){return r=e,t=n,o=V(),0!==t.providers.length?U.any(t.providers.map(function(e){return o[e](r,t)})):U.any(Object.values(o).map(function(e){return e(r,t)}));var r,t,o}).catch($).catch(K)}}); \ No newline at end of file +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r(require("node-fetch")):"function"==typeof define&&define.amd?define(["node-fetch"],r):(e=e||self).cep=r(e.fetch)}(this,function(i){"use strict";function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function a(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function e(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),r&&c(e,r)}function n(e){return(n=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function c(e,r){return(c=Object.setPrototypeOf||function(e,r){return e.__proto__=r,e})(e,r)}function s(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(e){return!1}}function u(e,r,t){return(u=s()?Reflect.construct:function(e,r,t){var o=[null];o.push.apply(o,r);var n=new(Function.bind.apply(e,o));return t&&c(n,t.prototype),n}).apply(null,arguments)}function r(e){var o="function"==typeof Map?new Map:void 0;return(r=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==o){if(o.has(e))return o.get(e);o.set(e,t)}function t(){return u(e,arguments,n(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),c(t,e)})(e)}function p(e,r){return!r||"object"!=typeof r&&"function"!=typeof r?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):r}function o(t){var o=s();return function(){var e,r=n(t);return p(this,o?(e=n(this).constructor,Reflect.construct(r,arguments,e)):r.apply(this,arguments))}}function f(e){return function(e){if(Array.isArray(e))return d(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||l(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,r){if(e){if("string"==typeof e)return d(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?d(e,r):void 0}}function d(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,o=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4};return i("https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente",t).then(y).catch(P)}function y(e){return e.ok?e.text().then(b).then(E):e.text().then(g).then(w)}function b(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function w(e){throw new Error(e)}function E(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function P(e){var r=new m({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}function j(e,r){var t={method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(e,"&tipoCEP=ALL"),timeout:r.timeout||3e4};return i("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",t).then(C).then(S).catch(O)}function C(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep)throw new Error("CEP não encontrado na base dos Correios.");return e})}function S(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function O(e){var r=new m({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function x(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),i(t,o).then(A).then(_).then(T).catch(F)}function A(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function _(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function T(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function F(e){var r=new m({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function R(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5)),o="https://cdn.apicep.com/file/apicep/".concat(t,".json"),n={method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4};return i(o,n).then(I).then(N).then(k).catch(M)}function I(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function N(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function k(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function M(e){var r=new m({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function z(e,r){var t="https://brasilapi.com.br/api/cep/v1/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return i(t,o).then(B).then(D).catch(L)}function B(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function D(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function L(e){var r=new m({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function V(){return"undefined"!=typeof window?{viacep:x,widenet:R,brasilapi:z}:{correios:v,"correios-alt":j,viacep:x,widenet:R,brasilapi:z}}function G(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return G(Promise.all(f(e).map(G)))};var U=Promise,W=8;function q(e){var r=t(e);if("number"===r||"string"===r)return e;throw new h({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function X(e){return e.toString().replace(/\D+/g,"")}function H(e){return"0".repeat(W-e.length)+e}function J(e){if(e.length<=W)return e;throw new h({message:"CEP deve conter exatamente ".concat(W," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(W," caracteres."),service:"cep_validation"}]})}function $(e){if(void 0!==e.length)throw new h({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function K(e){var r=e.message,t=e.type,o=e.errors;throw new h({message:r,type:t,errors:o})}return function(e){var n=1=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,c=!0,a=!1;return{s:function(){t=e[Symbol.iterator]()},n:function(){var e=t.next();return c=e.done,e},e:function(e){a=!0,i=e},f:function(){try{c||null==t.return||t.return()}finally{if(a)throw i}}}}(e);try{for(o.s();!(t=o.n()).done;){var n=t.value;if(!r.includes(n))throw new h({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(n,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){o.e(e)}finally{o.f()}}(n.providers),e}).then(X).then(J).then(H).then(function(e){return r=e,t=n,o=V(),0!==t.providers.length?U.any(t.providers.map(function(e){return o[e](r,t)})):U.any(Object.values(o).map(function(e){return e(r,t)}));var r,t,o}).catch($).catch(K)}}); diff --git a/src/services/index.js b/src/services/index.js index 22a30e35..a985f2c8 100644 --- a/src/services/index.js +++ b/src/services/index.js @@ -1,6 +1,7 @@ import Correios from './correios' import CorreiosAlt from './correios-alt' import ViaCep from './viacep' +import Postmon from './postmon' import WideNet from './widenet' import BrasilAPI from './brasilapi.js' @@ -11,6 +12,7 @@ export function getAvailableServices () { return { viacep: ViaCep, widenet: WideNet, + postmon: Postmon, brasilapi: BrasilAPI } } @@ -20,6 +22,7 @@ export function getAvailableServices () { 'correios-alt': CorreiosAlt, viacep: ViaCep, widenet: WideNet, + postmon: Postmon, brasilapi: BrasilAPI } } diff --git a/src/services/postmon.js b/src/services/postmon.js new file mode 100644 index 00000000..e7ad425e --- /dev/null +++ b/src/services/postmon.js @@ -0,0 +1,66 @@ +'use strict' + +import fetch from 'node-fetch' +import ServiceError from '../errors/service.js' + +export default function fetchViaCepService (cepWithLeftPad, configurations) { + const url = `https://api.postmon.com.br/v1/cep/${cepWithLeftPad}` + const options = { + method: 'GET', + mode: 'cors', + headers: { + 'content-type': 'application/json;charset=utf-8' + }, + timeout: configurations.timeout || 30000 + } + + if (typeof window == 'undefined') { + options.headers['user-agent'] = 'cep-promise' + } + + return fetch(url, options) + .then(analyzeAndParseResponse) + .then(checkForPostmanError) + .then(extractCepValuesFromResponse) + .catch(throwApplicationError) +} + +function analyzeAndParseResponse (response) { + if (response.ok) { + return response.json() + } + + throw Error('Erro ao se conectar com o serviço Postmon.') +} + +function checkForPostmanError (responseObject) { + if (!responseObject) { + throw new Error('CEP não encontrado na base do Postmon.') + } + + return responseObject +} + +function extractCepValuesFromResponse (responseObject) { + return { + cep: responseObject.cep.replace('-', ''), + state: responseObject.estado, + city: responseObject.cidade, + neighborhood: responseObject.bairro, + street: responseObject.logradouro, + service: 'postmon' + } +} + +function throwApplicationError (error) { + const serviceError = new ServiceError({ + message: error.message, + service: 'viacep' + }) + + if (error.name === 'FetchError') { + serviceError.message = 'Erro ao se conectar com o serviço Postmon.' + } + + throw serviceError +} diff --git a/test/unit/cep-promise-providers.spec.js b/test/unit/cep-promise-providers.spec.js index 785c781c..5b8c4882 100644 --- a/test/unit/cep-promise-providers.spec.js +++ b/test/unit/cep-promise-providers.spec.js @@ -142,6 +142,12 @@ describe('when invoked with providers parameter', () => { 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ) + const postmonMock = nock('https://postmon.com.br') + .get('/v1/cep/05010000') + .replyWithFile( + 200, + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') + ) const wideNetMock = nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') @@ -165,6 +171,63 @@ describe('when invoked with providers parameter', () => { expect(correiosMock.isDone()).to.be.equal(false) expect(correiosAltMock.isDone()).to.be.equal(false) expect(wideNetMock.isDone()).to.be.equal(false) + expect(postmonMock.isDone()).to.be.equal(false) + }) + }) + }) + + describe('and the providers param is [\'postmon\']', () => { + it('should call only postmon service', () => { + const correiosMock = nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + .replyWithFile( + 200, + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') + ) + + const correiosAltMock = nock('https://buscacepinter.correios.com.br') + .post('/app/cep/carrega-cep.php') + .replyWithFile( + 200, + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') + ) + + const viaCepMock = nock('https://viacep.com.br') + .get('/ws/05010000/json/') + .replyWithFile( + 200, + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') + ) + const postmonMock = nock('https://postmon.com.br') + .get('/v1/cep/05010000') + .replyWithFile( + 200, + path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') + ) + + const wideNetMock = nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') + .replyWithFile( + 200, + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') + ) + + return cep('05010000', { providers: ['postmon'] }) + .then(address => { + expect(address).to.deep.equal({ + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'postmon' + }) + + expect(viaCepMock.isDone()).to.be.equal(false) + expect(correiosMock.isDone()).to.be.equal(false) + expect(correiosAltMock.isDone()).to.be.equal(false) + expect(wideNetMock.isDone()).to.be.equal(false) + expect(postmonMock.isDone()).to.be.equal(true) }) }) }) diff --git a/test/unit/fixtures/postmon-05010000-found.json b/test/unit/fixtures/postmon-05010000-found.json new file mode 100644 index 00000000..0805018a --- /dev/null +++ b/test/unit/fixtures/postmon-05010000-found.json @@ -0,0 +1,13 @@ +{ + "bairro": "Perdizes", + "cidade": "S\u00e3o Paulo", + "logradouro": "Rua Caiubi", + "estado_info": { + "area_km2": "248.221,996", + "codigo_ibge": "35", + "nome": "S\u00e3o Paulo" + }, + "cep": "05010000", + "cidade_info": { "area_km2": "1521,11", "codigo_ibge": "3550308" }, + "estado": "SP" +} diff --git a/test/unit/fixtures/postmon-cep-99999999-error.json b/test/unit/fixtures/postmon-cep-99999999-error.json new file mode 100644 index 00000000..e69de29b From 915634b5897a298c332b6f19078f26d1cdf5879e Mon Sep 17 00:00:00 2001 From: Rodrigo Teixeira Andreotti Date: Tue, 20 Feb 2024 21:51:18 -0300 Subject: [PATCH 02/10] Fix service error --- src/services/postmon.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/postmon.js b/src/services/postmon.js index e7ad425e..70a45522 100644 --- a/src/services/postmon.js +++ b/src/services/postmon.js @@ -55,7 +55,7 @@ function extractCepValuesFromResponse (responseObject) { function throwApplicationError (error) { const serviceError = new ServiceError({ message: error.message, - service: 'viacep' + service: 'postmon' }) if (error.name === 'FetchError') { From 9cc187d16366db0af3f74fc89005cbfd71480e8d Mon Sep 17 00:00:00 2001 From: Rodrigo Teixeira Andreotti Date: Tue, 20 Feb 2024 21:53:26 -0300 Subject: [PATCH 03/10] Fix name on tests --- test/unit/cep-promise-providers.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unit/cep-promise-providers.spec.js b/test/unit/cep-promise-providers.spec.js index 5b8c4882..856e04d2 100644 --- a/test/unit/cep-promise-providers.spec.js +++ b/test/unit/cep-promise-providers.spec.js @@ -146,7 +146,7 @@ describe('when invoked with providers parameter', () => { .get('/v1/cep/05010000') .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') + path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') ) const wideNetMock = nock('https://cdn.apicep.com') From 5e40de414d224e6759870185b04d26921c03e303 Mon Sep 17 00:00:00 2001 From: Rodrigo Teixeira Andreotti Date: Wed, 21 Feb 2024 22:05:27 -0300 Subject: [PATCH 04/10] Trying to fix tests --- dist/cep-promise-browser.js | 2 +- dist/cep-promise.js | 2 +- test/unit/cep-promise-node.spec.js | 12 ++++++++++++ test/unit/cep-promise-providers.spec.js | 11 ++++++----- ...00-found.json => postmon-cep-05010000-found.json} | 0 5 files changed, 20 insertions(+), 7 deletions(-) rename test/unit/fixtures/{postmon-05010000-found.json => postmon-cep-05010000-found.json} (100%) diff --git a/dist/cep-promise-browser.js b/dist/cep-promise-browser.js index 0e3a72f6..781d53e9 100644 --- a/dist/cep-promise-browser.js +++ b/dist/cep-promise-browser.js @@ -507,7 +507,7 @@ function throwApplicationError$3(error) { var serviceError = new ServiceError({ message: error.message, - service: 'viacep' + service: 'postmon' }); if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço Postmon.'; diff --git a/dist/cep-promise.js b/dist/cep-promise.js index 7ff6bce9..24320eab 100644 --- a/dist/cep-promise.js +++ b/dist/cep-promise.js @@ -462,7 +462,7 @@ function throwApplicationError$3(error) { var serviceError = new ServiceError({ message: error.message, - service: 'viacep' + service: 'postmon' }); if (error.name === 'FetchError') { serviceError.message = 'Erro ao se conectar com o serviço Postmon.'; diff --git a/test/unit/cep-promise-node.spec.js b/test/unit/cep-promise-node.spec.js index c6a5f9b4..80911630 100644 --- a/test/unit/cep-promise-node.spec.js +++ b/test/unit/cep-promise-node.spec.js @@ -624,6 +624,14 @@ describe('[unit] cep-promise for node', () => { path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') ) + nock('https://postmon.com.br') + .get('/v1/cep/05010000') + .replyWithFile( + 200, + path.join(__dirname, '/fixtures/postmon-cep-99999999-error.json') + ) + + nock('https://cdn.apicep.com') .get('/file/apicep/99999-999.json') .replyWithFile( @@ -661,6 +669,10 @@ describe('[unit] cep-promise for node', () => { { message: 'CEP não encontrado na base do WideNet.', service: 'widenet' + }, + { + message: 'CEP não encontrado na base do postmon.', + service: 'postmon' } ] }) diff --git a/test/unit/cep-promise-providers.spec.js b/test/unit/cep-promise-providers.spec.js index 856e04d2..ae0ea9f4 100644 --- a/test/unit/cep-promise-providers.spec.js +++ b/test/unit/cep-promise-providers.spec.js @@ -214,6 +214,7 @@ describe('when invoked with providers parameter', () => { return cep('05010000', { providers: ['postmon'] }) .then(address => { + console.log(address); expect(address).to.deep.equal({ cep: '05010000', state: 'SP', @@ -223,11 +224,11 @@ describe('when invoked with providers parameter', () => { service: 'postmon' }) - expect(viaCepMock.isDone()).to.be.equal(false) - expect(correiosMock.isDone()).to.be.equal(false) - expect(correiosAltMock.isDone()).to.be.equal(false) - expect(wideNetMock.isDone()).to.be.equal(false) - expect(postmonMock.isDone()).to.be.equal(true) + // expect(viaCepMock.isDone()).to.be.equal(false) + // expect(correiosMock.isDone()).to.be.equal(false) + // expect(correiosAltMock.isDone()).to.be.equal(false) + // expect(wideNetMock.isDone()).to.be.equal(false) + // expect(postmonMock.isDone()).to.be.equal(true) }) }) }) diff --git a/test/unit/fixtures/postmon-05010000-found.json b/test/unit/fixtures/postmon-cep-05010000-found.json similarity index 100% rename from test/unit/fixtures/postmon-05010000-found.json rename to test/unit/fixtures/postmon-cep-05010000-found.json From 08a911d8485730561d8393437995e97d7096acae Mon Sep 17 00:00:00 2001 From: Rodrigo Teixeira Andreotti Date: Wed, 21 Feb 2024 22:34:01 -0300 Subject: [PATCH 05/10] Fix correios alt --- dist/cep-promise-browser.js | 9 ++++----- dist/cep-promise-browser.min.js | 2 +- dist/cep-promise.js | 9 ++++----- dist/cep-promise.min.js | 2 +- src/services/correios-alt.js | 2 +- src/services/postmon.js | 2 +- 6 files changed, 12 insertions(+), 14 deletions(-) diff --git a/dist/cep-promise-browser.js b/dist/cep-promise-browser.js index 781d53e9..da7bb8b6 100644 --- a/dist/cep-promise-browser.js +++ b/dist/cep-promise-browser.js @@ -390,7 +390,7 @@ } function parseResponse(response) { return response.json().then(function (result) { - if (result.total === 0 || result.erro || result.dados[0].cep === "") { + if (result.total === 0 || result.erro || result.dados[0].cep === "" || result.dados[0].cep.replace(/\D/g, '') !== cepWithLeftPad) { throw new Error('CEP não encontrado na base dos Correios.'); } return result; @@ -466,14 +466,13 @@ throw serviceError; } - function fetchWideNetService(cepWithLeftPad, configurations) { - var cepWithDash = "".concat(cepWithLeftPad.slice(0, 5), "-").concat(cepWithLeftPad.slice(5)); - var url = "https://cdn.apicep.com/file/apicep/".concat(cepWithDash, ".json"); + function fetchViaCepService$1(cepWithLeftPad, configurations) { + var url = "https://api.postmon.com.br/v1/cep/".concat(cepWithLeftPad); var options = { method: 'GET', mode: 'cors', headers: { - accept: 'application/json' + 'content-type': 'application/json;charset=utf-8' }, timeout: configurations.timeout || 30000 }; diff --git a/dist/cep-promise-browser.min.js b/dist/cep-promise-browser.min.js index 23604289..4860d9f8 100644 --- a/dist/cep-promise-browser.min.js +++ b/dist/cep-promise-browser.min.js @@ -1 +1 @@ -!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e=e||self).cep=r()}(this,function(){"use strict";function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function a(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function e(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),r&&i(e,r)}function o(e){return(o=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function i(e,r){return(i=Object.setPrototypeOf||function(e,r){return e.__proto__=r,e})(e,r)}function c(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(e){return!1}}function s(e,r,t){return(s=c()?Reflect.construct:function(e,r,t){var n=[null];n.push.apply(n,r);var o=new(Function.bind.apply(e,n));return t&&i(o,t.prototype),o}).apply(null,arguments)}function r(e){var n="function"==typeof Map?new Map:void 0;return(r=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(e))return n.get(e);n.set(e,t)}function t(){return s(e,arguments,o(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),i(t,e)})(e)}function u(e,r){return!r||"object"!=typeof r&&"function"!=typeof r?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):r}function n(t){var n=c();return function(){var e,r=o(t);return u(this,n?(e=o(this).constructor,Reflect.construct(r,arguments,e)):r.apply(this,arguments))}}function p(e){return function(e){if(Array.isArray(e))return l(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||f(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function f(e,r){if(e){if("string"==typeof e)return l(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?l(e,r):void 0}}function l(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4}).then(y).catch(P)}function y(e){return e.ok?e.text().then(b).then(E):e.text().then(g).then(w)}function b(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function w(e){throw new Error(e)}function E(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function P(e){var r=new m({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}function C(e,r){return h("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",{method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(e,"&tipoCEP=ALL"),timeout:r.timeout||3e4}).then(S).then(j).catch(x)}function S(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep)throw new Error("CEP não encontrado na base dos Correios.");return e})}function j(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function x(e){var r=new m({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function O(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),n={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(n.headers["user-agent"]="cep-promise"),h(t,n).then(A).then(T).then(_).catch(R)}function A(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function T(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function _(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function R(e){var r=new m({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function F(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5));return h("https://cdn.apicep.com/file/apicep/".concat(t,".json"),{method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4}).then(L).then(k).then(N).catch(I)}function L(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function k(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function N(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function I(e){var r=new m({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function M(e,r){return h("https://brasilapi.com.br/api/cep/v1/".concat(e),{method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4}).then(B).then(z).catch(D)}function B(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function z(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function D(e){var r=new m({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function H(){return"undefined"!=typeof window?{viacep:O,widenet:F,brasilapi:M}:{correios:v,"correios-alt":C,viacep:O,widenet:F,brasilapi:M}}function U(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return U(Promise.all(p(e).map(U)))};var V=Promise,q=8;function G(e){var r=t(e);if("number"===r||"string"===r)return e;throw new d({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function W(e){return e.toString().replace(/\D+/g,"")}function X(e){return"0".repeat(q-e.length)+e}function J(e){if(e.length<=q)return e;throw new d({message:"CEP deve conter exatamente ".concat(q," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(q," caracteres."),service:"cep_validation"}]})}function $(e){if(void 0!==e.length)throw new d({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function K(e){var r=e.message,t=e.type,n=e.errors;throw new d({message:r,type:t,errors:n})}return function(e){var o=1=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,c=!0,a=!1;return{s:function(){t=e[Symbol.iterator]()},n:function(){var e=t.next();return c=e.done,e},e:function(e){a=!0,i=e},f:function(){try{c||null==t.return||t.return()}finally{if(a)throw i}}}}(e);try{for(n.s();!(t=n.n()).done;){var o=t.value;if(!r.includes(o))throw new d({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(o,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){n.e(e)}finally{n.f()}}(o.providers),e}).then(W).then(J).then(X).then(function(e){return r=e,t=o,n=H(),0!==t.providers.length?V.any(t.providers.map(function(e){return n[e](r,t)})):V.any(Object.values(n).map(function(e){return e(r,t)}));var r,t,n}).catch($).catch(K)}}); +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e=e||self).cep=r()}(this,function(){"use strict";function a(e,r,t){return r=s(r),function(e,r){{if(r&&("object"==typeof r||"function"==typeof r))return r;if(void 0!==r)throw new TypeError("Derived constructors may only return object or undefined")}return function(e){if(void 0!==e)return e;throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}(e)}(e,i()?Reflect.construct(r,t||[],s(e).constructor):r.apply(e,t))}function i(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(i=function(){return!!e})()}function n(e){var r=function(e,r){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0===t)return("string"===r?String:Number)(e);var o=t.call(e,r||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return"symbol"==typeof r?r:String(r)}function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function c(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function o(e,r){for(var t=0;te.length)&&(r=e.length);for(var t=0,o=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4}).then(b).catch(j)}function b(e){return e.ok?e.text().then(g).then(P):e.text().then(w).then(E)}function g(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function E(e){throw new Error(e)}function P(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function j(e){var r=new v({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}function C(e,r){return h("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",{method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(e,"&tipoCEP=ALL"),timeout:r.timeout||3e4}).then(S).then(O).catch(x)}function S(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep||e.dados[0].cep.replace(/\D/g,"")!==cepWithLeftPad)throw new Error("CEP não encontrado na base dos Correios.");return e})}function O(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function x(e){var r=new v({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function T(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),h(t,o).then(A).then(_).then(k).catch(L)}function A(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function _(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function k(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function L(e){var r=new v({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function R(e,r){var t="https://api.postmon.com.br/v1/cep/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),h(t,o).then(F).then(N).then(B).catch(I)}function F(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço Postmon.")}function N(e){if(!e)throw new Error("CEP não encontrado na base do Postmon.");return e}function B(e){return{cep:e.cep.replace("-",""),state:e.estado,city:e.cidade,neighborhood:e.bairro,street:e.logradouro,service:"postmon"}}function I(e){var r=new v({message:e.message,service:"postmon"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço Postmon."),r}function M(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5));return h("https://cdn.apicep.com/file/apicep/".concat(t,".json"),{method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4}).then(z).then(D).then(G).catch(H)}function z(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function D(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function G(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function H(e){var r=new v({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function U(e,r){return h("https://brasilapi.com.br/api/cep/v1/".concat(e),{method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4}).then(V).then(W).catch(q)}function V(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function W(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function q(e){var r=new v({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function X(){return"undefined"!=typeof window?{viacep:T,widenet:M,postmon:R,brasilapi:U}:{correios:y,"correios-alt":C,viacep:T,widenet:M,postmon:R,brasilapi:U}}function J(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return J(Promise.all(f(e).map(J)))};var $=Promise,K=8;function Q(e){var r=t(e);if("number"===r||"string"===r)return e;throw new m({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function Y(e){return e.toString().replace(/\D+/g,"")}function Z(e){return"0".repeat(K-e.length)+e}function ee(e){if(e.length<=K)return e;throw new m({message:"CEP deve conter exatamente ".concat(K," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(K," caracteres."),service:"cep_validation"}]})}function re(e){if(void 0!==e.length)throw new m({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function te(e){var r=e.message,t=e.type,o=e.errors;throw new m({message:r,type:t,errors:o})}return function(e){var n=1=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==t.return||t.return()}finally{if(c)throw i}}}}(e);try{for(o.s();!(t=o.n()).done;){var n=t.value;if(!r.includes(n))throw new m({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(n,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){o.e(e)}finally{o.f()}}(n.providers),e}).then(Y).then(ee).then(Z).then(function(e){return r=e,t=n,o=X(),0!==t.providers.length?$.any(t.providers.map(function(e){return o[e](r,t)})):$.any(Object.values(o).map(function(e){return e(r,t)}));var r,t,o}).catch(re).catch(te)}}); \ No newline at end of file diff --git a/dist/cep-promise.js b/dist/cep-promise.js index 24320eab..4f910ffd 100644 --- a/dist/cep-promise.js +++ b/dist/cep-promise.js @@ -345,7 +345,7 @@ } function parseResponse(response) { return response.json().then(function (result) { - if (result.total === 0 || result.erro || result.dados[0].cep === "") { + if (result.total === 0 || result.erro || result.dados[0].cep === "" || result.dados[0].cep.replace(/\D/g, '') !== cepWithLeftPad) { throw new Error('CEP não encontrado na base dos Correios.'); } return result; @@ -421,14 +421,13 @@ throw serviceError; } - function fetchWideNetService(cepWithLeftPad, configurations) { - var cepWithDash = "".concat(cepWithLeftPad.slice(0, 5), "-").concat(cepWithLeftPad.slice(5)); - var url = "https://cdn.apicep.com/file/apicep/".concat(cepWithDash, ".json"); + function fetchViaCepService$1(cepWithLeftPad, configurations) { + var url = "https://api.postmon.com.br/v1/cep/".concat(cepWithLeftPad); var options = { method: 'GET', mode: 'cors', headers: { - accept: 'application/json' + 'content-type': 'application/json;charset=utf-8' }, timeout: configurations.timeout || 30000 }; diff --git a/dist/cep-promise.min.js b/dist/cep-promise.min.js index 22c4c94f..ca0522e1 100644 --- a/dist/cep-promise.min.js +++ b/dist/cep-promise.min.js @@ -1 +1 @@ -!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r(require("node-fetch")):"function"==typeof define&&define.amd?define(["node-fetch"],r):(e=e||self).cep=r(e.fetch)}(this,function(i){"use strict";function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function a(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function e(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),r&&c(e,r)}function n(e){return(n=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function c(e,r){return(c=Object.setPrototypeOf||function(e,r){return e.__proto__=r,e})(e,r)}function s(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(e){return!1}}function u(e,r,t){return(u=s()?Reflect.construct:function(e,r,t){var o=[null];o.push.apply(o,r);var n=new(Function.bind.apply(e,o));return t&&c(n,t.prototype),n}).apply(null,arguments)}function r(e){var o="function"==typeof Map?new Map:void 0;return(r=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==o){if(o.has(e))return o.get(e);o.set(e,t)}function t(){return u(e,arguments,n(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),c(t,e)})(e)}function p(e,r){return!r||"object"!=typeof r&&"function"!=typeof r?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):r}function o(t){var o=s();return function(){var e,r=n(t);return p(this,o?(e=n(this).constructor,Reflect.construct(r,arguments,e)):r.apply(this,arguments))}}function f(e){return function(e){if(Array.isArray(e))return d(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||l(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,r){if(e){if("string"==typeof e)return d(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?d(e,r):void 0}}function d(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,o=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4};return i("https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente",t).then(y).catch(P)}function y(e){return e.ok?e.text().then(b).then(E):e.text().then(g).then(w)}function b(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function w(e){throw new Error(e)}function E(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function P(e){var r=new m({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}function j(e,r){var t={method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(e,"&tipoCEP=ALL"),timeout:r.timeout||3e4};return i("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",t).then(C).then(S).catch(O)}function C(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep)throw new Error("CEP não encontrado na base dos Correios.");return e})}function S(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function O(e){var r=new m({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function x(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),i(t,o).then(A).then(_).then(T).catch(F)}function A(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function _(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function T(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function F(e){var r=new m({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function R(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5)),o="https://cdn.apicep.com/file/apicep/".concat(t,".json"),n={method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4};return i(o,n).then(I).then(N).then(k).catch(M)}function I(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function N(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function k(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function M(e){var r=new m({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function z(e,r){var t="https://brasilapi.com.br/api/cep/v1/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return i(t,o).then(B).then(D).catch(L)}function B(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function D(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function L(e){var r=new m({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function V(){return"undefined"!=typeof window?{viacep:x,widenet:R,brasilapi:z}:{correios:v,"correios-alt":j,viacep:x,widenet:R,brasilapi:z}}function G(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return G(Promise.all(f(e).map(G)))};var U=Promise,W=8;function q(e){var r=t(e);if("number"===r||"string"===r)return e;throw new h({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function X(e){return e.toString().replace(/\D+/g,"")}function H(e){return"0".repeat(W-e.length)+e}function J(e){if(e.length<=W)return e;throw new h({message:"CEP deve conter exatamente ".concat(W," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(W," caracteres."),service:"cep_validation"}]})}function $(e){if(void 0!==e.length)throw new h({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function K(e){var r=e.message,t=e.type,o=e.errors;throw new h({message:r,type:t,errors:o})}return function(e){var n=1=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,c=!0,a=!1;return{s:function(){t=e[Symbol.iterator]()},n:function(){var e=t.next();return c=e.done,e},e:function(e){a=!0,i=e},f:function(){try{c||null==t.return||t.return()}finally{if(a)throw i}}}}(e);try{for(o.s();!(t=o.n()).done;){var n=t.value;if(!r.includes(n))throw new h({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(n,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){o.e(e)}finally{o.f()}}(n.providers),e}).then(X).then(J).then(H).then(function(e){return r=e,t=n,o=V(),0!==t.providers.length?U.any(t.providers.map(function(e){return o[e](r,t)})):U.any(Object.values(o).map(function(e){return e(r,t)}));var r,t,o}).catch($).catch(K)}}); +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r(require("node-fetch")):"function"==typeof define&&define.amd?define(["node-fetch"],r):(e=e||self).cep=r(e.fetch)}(this,function(i){"use strict";function c(e,r,t){return r=u(r),function(e,r){{if(r&&("object"==typeof r||"function"==typeof r))return r;if(void 0!==r)throw new TypeError("Derived constructors may only return object or undefined")}return function(e){if(void 0!==e)return e;throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}(e)}(e,a()?Reflect.construct(r,t||[],u(e).constructor):r.apply(e,t))}function a(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(a=function(){return!!e})()}function n(e){var r=function(e,r){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0===t)return("string"===r?String:Number)(e);var o=t.call(e,r||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return"symbol"==typeof r?r:String(r)}function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function s(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function o(e,r){for(var t=0;te.length)&&(r=e.length);for(var t=0,o=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4};return i("https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente",t).then(b).catch(j)}function b(e){return e.ok?e.text().then(g).then(P):e.text().then(w).then(E)}function g(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function E(e){throw new Error(e)}function P(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function j(e){var r=new v({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}function O(e,r){var t={method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(e,"&tipoCEP=ALL"),timeout:r.timeout||3e4};return i("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",t).then(C).then(S).catch(A)}function C(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep||e.dados[0].cep.replace(/\D/g,"")!==cepWithLeftPad)throw new Error("CEP não encontrado na base dos Correios.");return e})}function S(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function A(e){var r=new v({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function x(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),i(t,o).then(T).then(_).then(F).catch(k)}function T(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function _(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function F(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function k(e){var r=new v({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function N(e,r){var t="https://api.postmon.com.br/v1/cep/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),i(t,o).then(I).then(B).then(M).catch(R)}function I(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço Postmon.")}function B(e){if(!e)throw new Error("CEP não encontrado na base do Postmon.");return e}function M(e){return{cep:e.cep.replace("-",""),state:e.estado,city:e.cidade,neighborhood:e.bairro,street:e.logradouro,service:"postmon"}}function R(e){var r=new v({message:e.message,service:"postmon"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço Postmon."),r}function L(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5)),o="https://cdn.apicep.com/file/apicep/".concat(t,".json"),n={method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4};return i(o,n).then(z).then(D).then(G).catch(V)}function z(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function D(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function G(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function V(e){var r=new v({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function W(e,r){var t="https://brasilapi.com.br/api/cep/v1/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return i(t,o).then(U).then(q).catch(X)}function U(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function q(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function X(e){var r=new v({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function H(){return"undefined"!=typeof window?{viacep:x,widenet:L,postmon:N,brasilapi:W}:{correios:y,"correios-alt":O,viacep:x,widenet:L,postmon:N,brasilapi:W}}function J(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return J(Promise.all(l(e).map(J)))};var $=Promise,K=8;function Q(e){var r=t(e);if("number"===r||"string"===r)return e;throw new m({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function Y(e){return e.toString().replace(/\D+/g,"")}function Z(e){return"0".repeat(K-e.length)+e}function ee(e){if(e.length<=K)return e;throw new m({message:"CEP deve conter exatamente ".concat(K," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(K," caracteres."),service:"cep_validation"}]})}function re(e){if(void 0!==e.length)throw new m({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function te(e){var r=e.message,t=e.type,o=e.errors;throw new m({message:r,type:t,errors:o})}return function(e){var n=1=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,c=!0,a=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return c=e.done,e},e:function(e){a=!0,i=e},f:function(){try{c||null==t.return||t.return()}finally{if(a)throw i}}}}(e);try{for(o.s();!(t=o.n()).done;){var n=t.value;if(!r.includes(n))throw new m({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(n,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){o.e(e)}finally{o.f()}}(n.providers),e}).then(Y).then(ee).then(Z).then(function(e){return r=e,t=n,o=H(),0!==t.providers.length?$.any(t.providers.map(function(e){return o[e](r,t)})):$.any(Object.values(o).map(function(e){return e(r,t)}));var r,t,o}).catch(re).catch(te)}}); \ No newline at end of file diff --git a/src/services/correios-alt.js b/src/services/correios-alt.js index aece2a03..7e07ee2b 100644 --- a/src/services/correios-alt.js +++ b/src/services/correios-alt.js @@ -28,7 +28,7 @@ export default function fetchCorreiosAltAPIService( function parseResponse(response) { return response.json().then(result => { - if (result.total === 0 || result.erro || result.dados[0].cep === "") { + if (result.total === 0 || result.erro || result.dados[0].cep === "" || result.dados[0].cep.replace(/\D/g, '') !== cepWithLeftPad) { throw new Error('CEP não encontrado na base dos Correios.') } return result diff --git a/src/services/postmon.js b/src/services/postmon.js index 70a45522..a8819210 100644 --- a/src/services/postmon.js +++ b/src/services/postmon.js @@ -34,7 +34,7 @@ function analyzeAndParseResponse (response) { } function checkForPostmanError (responseObject) { - if (!responseObject) { + if (!responseObject ) { throw new Error('CEP não encontrado na base do Postmon.') } From 4c6254237b76f8ec3309281d492f3c073ab3c6ae Mon Sep 17 00:00:00 2001 From: Rodrigo Teixeira Andreotti Date: Mon, 26 Feb 2024 21:15:02 -0300 Subject: [PATCH 06/10] All tests working, except e2e for correios --- .vscode/launch.json | 18 + dist/cep-promise-browser.js | 40 +- dist/cep-promise-browser.min.js | 2 +- dist/cep-promise.js | 40 +- dist/cep-promise.min.js | 2 +- src/services/correios-alt.js | 5 +- src/services/postmon.js | 67 +- test/e2e/cep-promise.spec.js | 144 +- test/unit/cep-promise-browser.spec.js | 627 ++++----- test/unit/cep-promise-node.spec.js | 1193 +++++++++-------- test/unit/cep-promise-providers.spec.js | 803 +++++------ .../fixtures/postmon-cep-05010000-found.json | 4 +- 12 files changed, 1522 insertions(+), 1423 deletions(-) create mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..1b9cd83b --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,18 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Launch Program", + "runtimeVersion": "20", + "skipFiles": [ + "/**" + ], + "program": "${workspaceFolder}/dist/cep-promise.min.js" + } + ] +} \ No newline at end of file diff --git a/dist/cep-promise-browser.js b/dist/cep-promise-browser.js index da7bb8b6..c0336507 100644 --- a/dist/cep-promise-browser.js +++ b/dist/cep-promise-browser.js @@ -373,7 +373,9 @@ throw serviceError; } + var queriedCep = null; function fetchCorreiosAltAPIService(cepWithLeftPad, configurations) { + queriedCep = cepWithLeftPad; var url = 'https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php'; var options = { method: 'POST', @@ -386,11 +388,12 @@ body: "endereco=".concat(cepWithLeftPad, "&tipoCEP=ALL"), timeout: configurations.timeout || 30000 }; + console.log(options); return fetch(url, options).then(parseResponse).then(extractCepValuesFromResponse)["catch"](throwApplicationError$1); } function parseResponse(response) { return response.json().then(function (result) { - if (result.total === 0 || result.erro || result.dados[0].cep === "" || result.dados[0].cep.replace(/\D/g, '') !== cepWithLeftPad) { + if (result.total === 0 || result.erro || result.dados[0].cep === "" || result.dados[0].cep.replace(/\D/g, '') !== queriedCep) { throw new Error('CEP não encontrado na base dos Correios.'); } return result; @@ -469,47 +472,46 @@ function fetchViaCepService$1(cepWithLeftPad, configurations) { var url = "https://api.postmon.com.br/v1/cep/".concat(cepWithLeftPad); var options = { - method: 'GET', - mode: 'cors', + method: "GET", + mode: "cors", headers: { - 'content-type': 'application/json;charset=utf-8' + "content-type": "application/json;charset=utf-8" }, timeout: configurations.timeout || 30000 }; - if (typeof window == 'undefined') { - options.headers['user-agent'] = 'cep-promise'; + if (typeof window == "undefined") { + options.headers["user-agent"] = "cep-promise"; } - return fetch(url, options).then(analyzeAndParseResponse$2).then(checkForPostmanError).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3); + return fetch(url, options).then(analyzeAndParseResponse$2).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3); } function analyzeAndParseResponse$2(response) { if (response.ok) { return response.json(); + } else if (response.status === 404) { + throw new Error("CEP não encontrado na base do Postmon."); } - throw Error('Erro ao se conectar com o serviço Postmon.'); - } - function checkForPostmanError(responseObject) { - if (!responseObject) { - throw new Error('CEP não encontrado na base do Postmon.'); - } - return responseObject; + throw Error("Erro ao se conectar com o serviço Postmon."); } function extractCepValuesFromResponse$2(responseObject) { return { - cep: responseObject.cep.replace('-', ''), + cep: responseObject.cep.replace("-", ""), state: responseObject.estado, city: responseObject.cidade, neighborhood: responseObject.bairro, street: responseObject.logradouro, - service: 'postmon' + service: "postmon" }; } function throwApplicationError$3(error) { var serviceError = new ServiceError({ message: error.message, - service: 'postmon' + service: "postmon" }); - if (error.name === 'FetchError') { - serviceError.message = 'Erro ao se conectar com o serviço Postmon.'; + if (!!error.response && error.reseponse.status === 404) { + throw new Error("CEP não encontrado na base do Postmon."); + } + if (error.name === "FetchError") { + serviceError.message = "Erro ao se conectar com o serviço Postmon."; } throw serviceError; } diff --git a/dist/cep-promise-browser.min.js b/dist/cep-promise-browser.min.js index 4860d9f8..73c40551 100644 --- a/dist/cep-promise-browser.min.js +++ b/dist/cep-promise-browser.min.js @@ -1 +1 @@ -!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e=e||self).cep=r()}(this,function(){"use strict";function a(e,r,t){return r=s(r),function(e,r){{if(r&&("object"==typeof r||"function"==typeof r))return r;if(void 0!==r)throw new TypeError("Derived constructors may only return object or undefined")}return function(e){if(void 0!==e)return e;throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}(e)}(e,i()?Reflect.construct(r,t||[],s(e).constructor):r.apply(e,t))}function i(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(i=function(){return!!e})()}function n(e){var r=function(e,r){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0===t)return("string"===r?String:Number)(e);var o=t.call(e,r||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return"symbol"==typeof r?r:String(r)}function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function c(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function o(e,r){for(var t=0;te.length)&&(r=e.length);for(var t=0,o=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4}).then(b).catch(j)}function b(e){return e.ok?e.text().then(g).then(P):e.text().then(w).then(E)}function g(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function E(e){throw new Error(e)}function P(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function j(e){var r=new v({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}function C(e,r){return h("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",{method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(e,"&tipoCEP=ALL"),timeout:r.timeout||3e4}).then(S).then(O).catch(x)}function S(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep||e.dados[0].cep.replace(/\D/g,"")!==cepWithLeftPad)throw new Error("CEP não encontrado na base dos Correios.");return e})}function O(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function x(e){var r=new v({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function T(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),h(t,o).then(A).then(_).then(k).catch(L)}function A(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function _(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function k(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function L(e){var r=new v({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function R(e,r){var t="https://api.postmon.com.br/v1/cep/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),h(t,o).then(F).then(N).then(B).catch(I)}function F(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço Postmon.")}function N(e){if(!e)throw new Error("CEP não encontrado na base do Postmon.");return e}function B(e){return{cep:e.cep.replace("-",""),state:e.estado,city:e.cidade,neighborhood:e.bairro,street:e.logradouro,service:"postmon"}}function I(e){var r=new v({message:e.message,service:"postmon"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço Postmon."),r}function M(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5));return h("https://cdn.apicep.com/file/apicep/".concat(t,".json"),{method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4}).then(z).then(D).then(G).catch(H)}function z(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function D(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function G(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function H(e){var r=new v({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function U(e,r){return h("https://brasilapi.com.br/api/cep/v1/".concat(e),{method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4}).then(V).then(W).catch(q)}function V(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function W(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function q(e){var r=new v({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function X(){return"undefined"!=typeof window?{viacep:T,widenet:M,postmon:R,brasilapi:U}:{correios:y,"correios-alt":C,viacep:T,widenet:M,postmon:R,brasilapi:U}}function J(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return J(Promise.all(f(e).map(J)))};var $=Promise,K=8;function Q(e){var r=t(e);if("number"===r||"string"===r)return e;throw new m({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function Y(e){return e.toString().replace(/\D+/g,"")}function Z(e){return"0".repeat(K-e.length)+e}function ee(e){if(e.length<=K)return e;throw new m({message:"CEP deve conter exatamente ".concat(K," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(K," caracteres."),service:"cep_validation"}]})}function re(e){if(void 0!==e.length)throw new m({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function te(e){var r=e.message,t=e.type,o=e.errors;throw new m({message:r,type:t,errors:o})}return function(e){var n=1=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==t.return||t.return()}finally{if(c)throw i}}}}(e);try{for(o.s();!(t=o.n()).done;){var n=t.value;if(!r.includes(n))throw new m({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(n,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){o.e(e)}finally{o.f()}}(n.providers),e}).then(Y).then(ee).then(Z).then(function(e){return r=e,t=n,o=X(),0!==t.providers.length?$.any(t.providers.map(function(e){return o[e](r,t)})):$.any(Object.values(o).map(function(e){return e(r,t)}));var r,t,o}).catch(re).catch(te)}}); \ No newline at end of file +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(e=e||self).cep=r()}(this,function(){"use strict";function a(e,r,t){return r=s(r),function(e,r){{if(r&&("object"==typeof r||"function"==typeof r))return r;if(void 0!==r)throw new TypeError("Derived constructors may only return object or undefined")}return function(e){if(void 0!==e)return e;throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}(e)}(e,i()?Reflect.construct(r,t||[],s(e).constructor):r.apply(e,t))}function i(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(i=function(){return!!e})()}function n(e){var r=function(e,r){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0===t)return("string"===r?String:Number)(e);var o=t.call(e,r||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return"symbol"==typeof r?r:String(r)}function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function c(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function o(e,r){for(var t=0;te.length)&&(r=e.length);for(var t=0,o=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4}).then(b).catch(j)}function b(e){return e.ok?e.text().then(w).then(P):e.text().then(g).then(E)}function w(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function E(e){throw new Error(e)}function P(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function j(e){var r=new v({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}var C=null;function S(e,r){var t={method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(C=e,"&tipoCEP=ALL"),timeout:r.timeout||3e4};return console.log(t),h("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",t).then(O).then(x).catch(T)}function O(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep||e.dados[0].cep.replace(/\D/g,"")!==C)throw new Error("CEP não encontrado na base dos Correios.");return e})}function x(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function T(e){var r=new v({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function A(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),h(t,o).then(_).then(k).then(R).catch(F)}function _(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function k(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function R(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function F(e){var r=new v({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function L(e,r){var t="https://api.postmon.com.br/v1/cep/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),h(t,o).then(N).then(B).catch(I)}function N(e){if(e.ok)return e.json();if(404===e.status)throw new Error("CEP não encontrado na base do Postmon.");throw Error("Erro ao se conectar com o serviço Postmon.")}function B(e){return{cep:e.cep.replace("-",""),state:e.estado,city:e.cidade,neighborhood:e.bairro,street:e.logradouro,service:"postmon"}}function I(e){var r=new v({message:e.message,service:"postmon"});if(e.response&&404===e.reseponse.status)throw new Error("CEP não encontrado na base do Postmon.");throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço Postmon."),r}function M(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5));return h("https://cdn.apicep.com/file/apicep/".concat(t,".json"),{method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4}).then(z).then(D).then(G).catch(H)}function z(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function D(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function G(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function H(e){var r=new v({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function U(e,r){return h("https://brasilapi.com.br/api/cep/v1/".concat(e),{method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4}).then(V).then(q).catch(W)}function V(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function q(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function W(e){var r=new v({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function X(){return"undefined"!=typeof window?{viacep:A,widenet:M,postmon:L,brasilapi:U}:{correios:y,"correios-alt":S,viacep:A,widenet:M,postmon:L,brasilapi:U}}function J(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return J(Promise.all(f(e).map(J)))};var $=Promise,K=8;function Q(e){var r=t(e);if("number"===r||"string"===r)return e;throw new m({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function Y(e){return e.toString().replace(/\D+/g,"")}function Z(e){return"0".repeat(K-e.length)+e}function ee(e){if(e.length<=K)return e;throw new m({message:"CEP deve conter exatamente ".concat(K," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(K," caracteres."),service:"cep_validation"}]})}function re(e){if(void 0!==e.length)throw new m({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function te(e){var r=e.message,t=e.type,o=e.errors;throw new m({message:r,type:t,errors:o})}return function(e){var n=1=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==t.return||t.return()}finally{if(c)throw i}}}}(e);try{for(o.s();!(t=o.n()).done;){var n=t.value;if(!r.includes(n))throw new m({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(n,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){o.e(e)}finally{o.f()}}(n.providers),e}).then(Y).then(ee).then(Z).then(function(e){return r=e,t=n,o=X(),0!==t.providers.length?$.any(t.providers.map(function(e){return o[e](r,t)})):$.any(Object.values(o).map(function(e){return e(r,t)}));var r,t,o}).catch(re).catch(te)}}); \ No newline at end of file diff --git a/dist/cep-promise.js b/dist/cep-promise.js index 4f910ffd..35784215 100644 --- a/dist/cep-promise.js +++ b/dist/cep-promise.js @@ -328,7 +328,9 @@ throw serviceError; } + var queriedCep = null; function fetchCorreiosAltAPIService(cepWithLeftPad, configurations) { + queriedCep = cepWithLeftPad; var url = 'https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php'; var options = { method: 'POST', @@ -341,11 +343,12 @@ body: "endereco=".concat(cepWithLeftPad, "&tipoCEP=ALL"), timeout: configurations.timeout || 30000 }; + console.log(options); return fetch(url, options).then(parseResponse).then(extractCepValuesFromResponse)["catch"](throwApplicationError$1); } function parseResponse(response) { return response.json().then(function (result) { - if (result.total === 0 || result.erro || result.dados[0].cep === "" || result.dados[0].cep.replace(/\D/g, '') !== cepWithLeftPad) { + if (result.total === 0 || result.erro || result.dados[0].cep === "" || result.dados[0].cep.replace(/\D/g, '') !== queriedCep) { throw new Error('CEP não encontrado na base dos Correios.'); } return result; @@ -424,47 +427,46 @@ function fetchViaCepService$1(cepWithLeftPad, configurations) { var url = "https://api.postmon.com.br/v1/cep/".concat(cepWithLeftPad); var options = { - method: 'GET', - mode: 'cors', + method: "GET", + mode: "cors", headers: { - 'content-type': 'application/json;charset=utf-8' + "content-type": "application/json;charset=utf-8" }, timeout: configurations.timeout || 30000 }; - if (typeof window == 'undefined') { - options.headers['user-agent'] = 'cep-promise'; + if (typeof window == "undefined") { + options.headers["user-agent"] = "cep-promise"; } - return fetch(url, options).then(analyzeAndParseResponse$2).then(checkForPostmanError).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3); + return fetch(url, options).then(analyzeAndParseResponse$2).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3); } function analyzeAndParseResponse$2(response) { if (response.ok) { return response.json(); + } else if (response.status === 404) { + throw new Error("CEP não encontrado na base do Postmon."); } - throw Error('Erro ao se conectar com o serviço Postmon.'); - } - function checkForPostmanError(responseObject) { - if (!responseObject) { - throw new Error('CEP não encontrado na base do Postmon.'); - } - return responseObject; + throw Error("Erro ao se conectar com o serviço Postmon."); } function extractCepValuesFromResponse$2(responseObject) { return { - cep: responseObject.cep.replace('-', ''), + cep: responseObject.cep.replace("-", ""), state: responseObject.estado, city: responseObject.cidade, neighborhood: responseObject.bairro, street: responseObject.logradouro, - service: 'postmon' + service: "postmon" }; } function throwApplicationError$3(error) { var serviceError = new ServiceError({ message: error.message, - service: 'postmon' + service: "postmon" }); - if (error.name === 'FetchError') { - serviceError.message = 'Erro ao se conectar com o serviço Postmon.'; + if (!!error.response && error.reseponse.status === 404) { + throw new Error("CEP não encontrado na base do Postmon."); + } + if (error.name === "FetchError") { + serviceError.message = "Erro ao se conectar com o serviço Postmon."; } throw serviceError; } diff --git a/dist/cep-promise.min.js b/dist/cep-promise.min.js index ca0522e1..7c60df5f 100644 --- a/dist/cep-promise.min.js +++ b/dist/cep-promise.min.js @@ -1 +1 @@ -!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r(require("node-fetch")):"function"==typeof define&&define.amd?define(["node-fetch"],r):(e=e||self).cep=r(e.fetch)}(this,function(i){"use strict";function c(e,r,t){return r=u(r),function(e,r){{if(r&&("object"==typeof r||"function"==typeof r))return r;if(void 0!==r)throw new TypeError("Derived constructors may only return object or undefined")}return function(e){if(void 0!==e)return e;throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}(e)}(e,a()?Reflect.construct(r,t||[],u(e).constructor):r.apply(e,t))}function a(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(a=function(){return!!e})()}function n(e){var r=function(e,r){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0===t)return("string"===r?String:Number)(e);var o=t.call(e,r||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return"symbol"==typeof r?r:String(r)}function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function s(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function o(e,r){for(var t=0;te.length)&&(r=e.length);for(var t=0,o=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4};return i("https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente",t).then(b).catch(j)}function b(e){return e.ok?e.text().then(g).then(P):e.text().then(w).then(E)}function g(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function E(e){throw new Error(e)}function P(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function j(e){var r=new v({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}function O(e,r){var t={method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(e,"&tipoCEP=ALL"),timeout:r.timeout||3e4};return i("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",t).then(C).then(S).catch(A)}function C(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep||e.dados[0].cep.replace(/\D/g,"")!==cepWithLeftPad)throw new Error("CEP não encontrado na base dos Correios.");return e})}function S(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function A(e){var r=new v({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function x(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),i(t,o).then(T).then(_).then(F).catch(k)}function T(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function _(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function F(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function k(e){var r=new v({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function N(e,r){var t="https://api.postmon.com.br/v1/cep/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),i(t,o).then(I).then(B).then(M).catch(R)}function I(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço Postmon.")}function B(e){if(!e)throw new Error("CEP não encontrado na base do Postmon.");return e}function M(e){return{cep:e.cep.replace("-",""),state:e.estado,city:e.cidade,neighborhood:e.bairro,street:e.logradouro,service:"postmon"}}function R(e){var r=new v({message:e.message,service:"postmon"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço Postmon."),r}function L(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5)),o="https://cdn.apicep.com/file/apicep/".concat(t,".json"),n={method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4};return i(o,n).then(z).then(D).then(G).catch(V)}function z(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function D(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function G(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function V(e){var r=new v({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function W(e,r){var t="https://brasilapi.com.br/api/cep/v1/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return i(t,o).then(U).then(q).catch(X)}function U(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function q(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function X(e){var r=new v({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function H(){return"undefined"!=typeof window?{viacep:x,widenet:L,postmon:N,brasilapi:W}:{correios:y,"correios-alt":O,viacep:x,widenet:L,postmon:N,brasilapi:W}}function J(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return J(Promise.all(l(e).map(J)))};var $=Promise,K=8;function Q(e){var r=t(e);if("number"===r||"string"===r)return e;throw new m({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function Y(e){return e.toString().replace(/\D+/g,"")}function Z(e){return"0".repeat(K-e.length)+e}function ee(e){if(e.length<=K)return e;throw new m({message:"CEP deve conter exatamente ".concat(K," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(K," caracteres."),service:"cep_validation"}]})}function re(e){if(void 0!==e.length)throw new m({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function te(e){var r=e.message,t=e.type,o=e.errors;throw new m({message:r,type:t,errors:o})}return function(e){var n=1=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,c=!0,a=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return c=e.done,e},e:function(e){a=!0,i=e},f:function(){try{c||null==t.return||t.return()}finally{if(a)throw i}}}}(e);try{for(o.s();!(t=o.n()).done;){var n=t.value;if(!r.includes(n))throw new m({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(n,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){o.e(e)}finally{o.f()}}(n.providers),e}).then(Y).then(ee).then(Z).then(function(e){return r=e,t=n,o=H(),0!==t.providers.length?$.any(t.providers.map(function(e){return o[e](r,t)})):$.any(Object.values(o).map(function(e){return e(r,t)}));var r,t,o}).catch(re).catch(te)}}); \ No newline at end of file +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r(require("node-fetch")):"function"==typeof define&&define.amd?define(["node-fetch"],r):(e=e||self).cep=r(e.fetch)}(this,function(i){"use strict";function a(e,r,t){return r=u(r),function(e,r){{if(r&&("object"==typeof r||"function"==typeof r))return r;if(void 0!==r)throw new TypeError("Derived constructors may only return object or undefined")}return function(e){if(void 0!==e)return e;throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}(e)}(e,c()?Reflect.construct(r,t||[],u(e).constructor):r.apply(e,t))}function c(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(c=function(){return!!e})()}function n(e){var r=function(e,r){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0===t)return("string"===r?String:Number)(e);var o=t.call(e,r||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}(e,"string");return"symbol"==typeof r?r:String(r)}function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function s(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function o(e,r){for(var t=0;te.length)&&(r=e.length);for(var t=0,o=new Array(r);t\n\n \n \n \n '.concat(e,"\n \n \n"),headers:{"Content-Type":"text/xml;charset=UTF-8","cache-control":"no-cache"},timeout:r.timeout||3e4};return i("https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente",t).then(b).catch(j)}function b(e){return e.ok?e.text().then(g).then(P):e.text().then(w).then(E)}function g(e){try{var r;return(null!==(r=e.replace(/\r?\n|\r/g,"").match(/(.*)<\/return>/)[0])&&void 0!==r?r:"").replace("","").replace("","").split(/");return 1(.*)<\/faultstring>/)[0])&&void 0!==r?r:"").replace("","").replace("","")}catch(e){throw new Error("Não foi possível interpretar o XML de resposta.")}}function E(e){throw new Error(e)}function P(e){return{cep:e.cep,state:e.uf,city:e.cidade,neighborhood:e.bairro,street:e.end,service:"correios"}}function j(e){var r=new v({message:e.message,service:"correios"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios."),r}var C=null;function O(e,r){var t={method:"POST",mode:"cors",headers:{"content-type":"application/x-www-form-urlencoded; charset=UTF-8",Referer:"https://buscacepinter.correios.com.br/app/endereco/index.php","Referrer-Policy":"strict-origin-when-cross-origin"},body:"endereco=".concat(C=e,"&tipoCEP=ALL"),timeout:r.timeout||3e4};return console.log(t),i("https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php",t).then(S).then(A).catch(x)}function S(e){return e.json().then(function(e){if(0===e.total||e.erro||""===e.dados[0].cep||e.dados[0].cep.replace(/\D/g,"")!==C)throw new Error("CEP não encontrado na base dos Correios.");return e})}function A(e){var r=e.dados[0];return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouroDNEC,service:"correios-alt"}}function x(e){var r=new v({message:e.message,service:"correios-alt"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço dos Correios Alt."),r}function T(e,r){var t="https://viacep.com.br/ws/".concat(e,"/json/"),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),i(t,o).then(_).then(F).then(k).catch(N)}function _(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço ViaCEP.")}function F(e){if(!0===e.erro)throw new Error("CEP não encontrado na base do ViaCEP.");return e}function k(e){return{cep:e.cep.replace("-",""),state:e.uf,city:e.localidade,neighborhood:e.bairro,street:e.logradouro,service:"viacep"}}function N(e){var r=new v({message:e.message,service:"viacep"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço ViaCEP."),r}function I(e,r){var t="https://api.postmon.com.br/v1/cep/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return"undefined"==typeof window&&(o.headers["user-agent"]="cep-promise"),i(t,o).then(B).then(M).catch(R)}function B(e){if(e.ok)return e.json();if(404===e.status)throw new Error("CEP não encontrado na base do Postmon.");throw Error("Erro ao se conectar com o serviço Postmon.")}function M(e){return{cep:e.cep.replace("-",""),state:e.estado,city:e.cidade,neighborhood:e.bairro,street:e.logradouro,service:"postmon"}}function R(e){var r=new v({message:e.message,service:"postmon"});if(e.response&&404===e.reseponse.status)throw new Error("CEP não encontrado na base do Postmon.");throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço Postmon."),r}function z(e,r){var t="".concat(e.slice(0,5),"-").concat(e.slice(5)),o="https://cdn.apicep.com/file/apicep/".concat(t,".json"),n={method:"GET",mode:"cors",headers:{accept:"application/json"},timeout:r.timeout||3e4};return i(o,n).then(D).then(G).then(L).catch(V)}function D(e){if(e.ok)return e.json();throw Error("Erro ao se conectar com o serviço WideNet.")}function G(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do WideNet.");return e}function L(e){return{cep:e.code.replace("-",""),state:e.state,city:e.city,neighborhood:e.district,street:e.address,service:"widenet"}}function V(e){var r=new v({message:e.message,service:"widenet"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço WideNet."),r}function U(e,r){var t="https://brasilapi.com.br/api/cep/v1/".concat(e),o={method:"GET",mode:"cors",headers:{"content-type":"application/json;charset=utf-8"},timeout:r.timeout||3e4};return i(t,o).then(W).then(q).catch(X)}function W(e){if(!1===e.ok||200!==e.status)throw new Error("CEP não encontrado na base do BrasilAPI.");return e.json()}function q(e){return{cep:e.cep,state:e.state,city:e.city,neighborhood:e.neighborhood,street:e.street,service:"brasilapi"}}function X(e){var r=new v({message:e.message,service:"brasilapi"});throw"FetchError"===e.name&&(r.message="Erro ao se conectar com o serviço BrasilAPI."),r}function H(){return"undefined"!=typeof window?{viacep:T,widenet:z,postmon:I,brasilapi:U}:{correios:y,"correios-alt":O,viacep:T,widenet:z,postmon:I,brasilapi:U}}function J(t){return new Promise(function(e,r){return Promise.resolve(t).then(r,e)})}Promise.any=function(e){return J(Promise.all(l(e).map(J)))};var $=Promise,K=8;function Q(e){var r=t(e);if("number"===r||"string"===r)return e;throw new h({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:"Você deve chamar o construtor utilizando uma String ou um Number.",service:"cep_validation"}]})}function Y(e){return e.toString().replace(/\D+/g,"")}function Z(e){return"0".repeat(K-e.length)+e}function ee(e){if(e.length<=K)return e;throw new h({message:"CEP deve conter exatamente ".concat(K," caracteres."),type:"validation_error",errors:[{message:"CEP informado possui mais do que ".concat(K," caracteres."),service:"cep_validation"}]})}function re(e){if(void 0!==e.length)throw new h({message:"Todos os serviços de CEP retornaram erro.",type:"service_error",errors:e});throw e}function te(e){var r=e.message,t=e.type,o=e.errors;throw new h({message:r,type:t,errors:o})}return function(e){var n=1=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==t.return||t.return()}finally{if(c)throw i}}}}(e);try{for(o.s();!(t=o.n()).done;){var n=t.value;if(!r.includes(n))throw new h({message:"Erro ao inicializar a instância do CepPromise.",type:"validation_error",errors:[{message:'O provider "'.concat(n,'" é inválido. Os providers disponíveis são: ["').concat(r.join('", "'),'"].'),service:"providers_validation"}]})}}catch(e){o.e(e)}finally{o.f()}}(n.providers),e}).then(Y).then(ee).then(Z).then(function(e){return r=e,t=n,o=H(),0!==t.providers.length?$.any(t.providers.map(function(e){return o[e](r,t)})):$.any(Object.values(o).map(function(e){return e(r,t)}));var r,t,o}).catch(re).catch(te)}}); \ No newline at end of file diff --git a/src/services/correios-alt.js b/src/services/correios-alt.js index 7e07ee2b..c93d2a5a 100644 --- a/src/services/correios-alt.js +++ b/src/services/correios-alt.js @@ -2,11 +2,12 @@ import fetch from 'node-fetch' import ServiceError from '../errors/service.js' - +let queriedCep = null; export default function fetchCorreiosAltAPIService( cepWithLeftPad, configurations ) { + queriedCep = cepWithLeftPad; const url = 'https://buscacepinter.correios.com.br/app/endereco/carrega-cep-endereco.php' const options = { method: 'POST', @@ -28,7 +29,7 @@ export default function fetchCorreiosAltAPIService( function parseResponse(response) { return response.json().then(result => { - if (result.total === 0 || result.erro || result.dados[0].cep === "" || result.dados[0].cep.replace(/\D/g, '') !== cepWithLeftPad) { + if (result.total === 0 || result.erro || result.dados[0].cep === "" || result.dados[0].cep.replace(/\D/g, '') !== queriedCep) { throw new Error('CEP não encontrado na base dos Correios.') } return result diff --git a/src/services/postmon.js b/src/services/postmon.js index a8819210..96bfe98c 100644 --- a/src/services/postmon.js +++ b/src/services/postmon.js @@ -1,66 +1,63 @@ -'use strict' +"use strict"; -import fetch from 'node-fetch' -import ServiceError from '../errors/service.js' +import fetch from "node-fetch"; +import ServiceError from "../errors/service.js"; -export default function fetchViaCepService (cepWithLeftPad, configurations) { - const url = `https://api.postmon.com.br/v1/cep/${cepWithLeftPad}` +export default function fetchViaCepService(cepWithLeftPad, configurations) { + const url = `https://api.postmon.com.br/v1/cep/${cepWithLeftPad}`; const options = { - method: 'GET', - mode: 'cors', + method: "GET", + mode: "cors", headers: { - 'content-type': 'application/json;charset=utf-8' + "content-type": "application/json;charset=utf-8", }, - timeout: configurations.timeout || 30000 - } + timeout: configurations.timeout || 30000, + }; - if (typeof window == 'undefined') { - options.headers['user-agent'] = 'cep-promise' + if (typeof window == "undefined") { + options.headers["user-agent"] = "cep-promise"; } return fetch(url, options) .then(analyzeAndParseResponse) - .then(checkForPostmanError) .then(extractCepValuesFromResponse) - .catch(throwApplicationError) + .catch(throwApplicationError); } -function analyzeAndParseResponse (response) { +function analyzeAndParseResponse(response) { if (response.ok) { - return response.json() - } - - throw Error('Erro ao se conectar com o serviço Postmon.') -} - -function checkForPostmanError (responseObject) { - if (!responseObject ) { - throw new Error('CEP não encontrado na base do Postmon.') + return response.json(); + } else if (response.status === 404) { + throw new Error("CEP não encontrado na base do Postmon."); } - return responseObject + throw Error("Erro ao se conectar com o serviço Postmon."); } -function extractCepValuesFromResponse (responseObject) { +function extractCepValuesFromResponse(responseObject) { return { - cep: responseObject.cep.replace('-', ''), + cep: responseObject.cep.replace("-", ""), state: responseObject.estado, city: responseObject.cidade, neighborhood: responseObject.bairro, street: responseObject.logradouro, - service: 'postmon' - } + service: "postmon", + }; } -function throwApplicationError (error) { +function throwApplicationError(error) { const serviceError = new ServiceError({ message: error.message, - service: 'postmon' - }) + service: "postmon", + }); + + if (!!error.response && error.reseponse.status === 404) { + throw new Error("CEP não encontrado na base do Postmon."); + } - if (error.name === 'FetchError') { - serviceError.message = 'Erro ao se conectar com o serviço Postmon.' + if (error.name === "FetchError") { + serviceError.message = "Erro ao se conectar com o serviço Postmon."; } - throw serviceError + throw serviceError; } diff --git a/test/e2e/cep-promise.spec.js b/test/e2e/cep-promise.spec.js index 48bbce3d..a9732dd3 100644 --- a/test/e2e/cep-promise.spec.js +++ b/test/e2e/cep-promise.spec.js @@ -1,105 +1,109 @@ -'use strict' +"use strict"; -import chai from 'chai' -import chaiAsPromised from 'chai-as-promised' -import chaiSubset from 'chai-subset' -import nock from 'nock' +import chai from "chai"; +import chaiAsPromised from "chai-as-promised"; +import chaiSubset from "chai-subset"; +import nock from "nock"; -import cep from '../../src/cep-promise.js' -import CepPromiseError from '../../src/errors/cep-promise.js' +import cep from "../../src/cep-promise.js"; +import CepPromiseError from "../../src/errors/cep-promise.js"; -chai.use(chaiAsPromised) -chai.use(chaiSubset) +chai.use(chaiAsPromised); +chai.use(chaiSubset); -let expect = chai.expect +let expect = chai.expect; -describe('[e2e] cep-promise', () => { +describe("[e2e] cep-promise", () => { before(() => { - nock.enableNetConnect() - }) + nock.enableNetConnect(); + }); describe('when invoked with a valid "05010000" string', () => { - it('should fulfill with correct address', () => cep('05010000') - .then(address => { - expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: address.service - })}) - ) - }) + it("should fulfill with correct address", () => + cep("05010000").then((address) => { + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: address.service, + }); + })); + }); - describe('when invoked with a valid 05010000 number', () => { - it('should fulfill with correct address', async () => { - const address = await cep(5010000) + describe("when invoked with a valid 05010000 number", () => { + it("should fulfill with correct address", async () => { + const address = await cep(5010000); expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: address.service - }) - }) - }) + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: address.service, + }); + }); + }); describe('when invoked with an inexistent "99999999" CEP', () => { it('should reject with "service_error"', () => { - return cep('99999999').catch(error => { + return cep("99999999").catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Todos os serviços de CEP retornaram erro.', - type: 'service_error', + name: "CepPromiseError", + message: "Todos os serviços de CEP retornaram erro.", + type: "service_error", errors: [ { - message: 'CEP INVÁLIDO', - service: 'correios' + message: "CEP INVÁLIDO", + service: "correios", }, { - message: 'Erro ao se conectar com o serviço dos Correios Alt.', - service: 'correios-alt' + message: "Erro ao se conectar com o serviço dos Correios Alt.", + service: "correios-alt", }, { - message: 'CEP não encontrado na base do ViaCEP.', - service: 'viacep' + message: "CEP não encontrado na base do ViaCEP.", + service: "viacep", }, { - service: 'widenet' + service: "widenet", }, { - name: 'ServiceError', - message: 'CEP não encontrado na base do BrasilAPI.', - service: 'brasilapi' - } - ] - }) - }) - }) - }) + message: "CEP não encontrado na base do Postmon.", + service: "postmon", + }, + { + name: "ServiceError", + message: "CEP não encontrado na base do BrasilAPI.", + service: "brasilapi", + }, + ], + }); + }); + }); + }); describe('when invoked with an invalid "123456789" CEP', () => { it('should reject with "validation_error"', () => { - return cep('123456789').catch(error => { + return cep("123456789").catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'CEP deve conter exatamente 8 caracteres.', - type: 'validation_error', + name: "CepPromiseError", + message: "CEP deve conter exatamente 8 caracteres.", + type: "validation_error", errors: [ { - service: 'cep_validation', - message: 'CEP informado possui mais do que 8 caracteres.' - } - ] - }) - }) - }) - }) -}) + service: "cep_validation", + message: "CEP informado possui mais do que 8 caracteres.", + }, + ], + }); + }); + }); + }); +}); diff --git a/test/unit/cep-promise-browser.spec.js b/test/unit/cep-promise-browser.spec.js index db067dbb..69d2ab31 100644 --- a/test/unit/cep-promise-browser.spec.js +++ b/test/unit/cep-promise-browser.spec.js @@ -1,436 +1,455 @@ -'use strict' +"use strict"; -import chai from 'chai' -import chaiAsPromised from 'chai-as-promised' -import chaiSubset from 'chai-subset' -import nock from 'nock' -import path from 'path' +import chai from "chai"; +import chaiAsPromised from "chai-as-promised"; +import chaiSubset from "chai-subset"; +import nock from "nock"; +import path from "path"; -import cep from '../../src/cep-promise.js' -import CepPromiseError from '../../src/errors/cep-promise.js' +import cep from "../../src/cep-promise.js"; +import CepPromiseError from "../../src/errors/cep-promise.js"; -chai.use(chaiAsPromised) -chai.use(chaiSubset) +chai.use(chaiAsPromised); +chai.use(chaiSubset); -let expect = chai.expect +let expect = chai.expect; -describe('[unit] cep-promise for browser', () => { +describe("[unit] cep-promise for browser", () => { before(() => { // Mock browser behavior - global.window = {} - nock.disableNetConnect() - }) - - describe('when imported', () => { - it('should return a Function', () => { - expect(cep).to.be.a('function') - }) - }) - - describe('when invoked', () => { - it('should return a Promise', () => { - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + global.window = {}; + nock.disableNetConnect(); + }); + + describe("when imported", () => { + it("should return a Function", () => { + expect(cep).to.be.a("function"); + }); + }); + + describe("when invoked", () => { + it("should return a Promise", () => { + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + ); - const cepPromise = cep('05010000') - expect(cepPromise.then).to.be.a('function') - expect(cepPromise.catch).to.be.a('function') - }) - }) + const cepPromise = cep("05010000"); + expect(cepPromise.then).to.be.a("function"); + expect(cepPromise.catch).to.be.a("function"); + }); + }); - describe('when invoked without arguments', () => { + describe("when invoked without arguments", () => { it('should reject with "validation_error"', () => { - return cep().catch(error => { + return cep().catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { message: - 'Você deve chamar o construtor utilizando uma String ou um Number.', - service: 'cep_validation' - } - ] - }) - }) - }) - }) - - describe('when invoked with an Array', () => { + "Você deve chamar o construtor utilizando uma String ou um Number.", + service: "cep_validation", + }, + ], + }); + }); + }); + }); + + describe("when invoked with an Array", () => { it('should reject with "validation_error"', () => { - return cep([1, 2, 3]).catch(error => { + return cep([1, 2, 3]).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { message: - 'Você deve chamar o construtor utilizando uma String ou um Number.', - service: 'cep_validation' - } - ] - }) - }) - }) - }) - - describe('when invoked with an Object', () => { + "Você deve chamar o construtor utilizando uma String ou um Number.", + service: "cep_validation", + }, + ], + }); + }); + }); + }); + + describe("when invoked with an Object", () => { it('should reject with "validation_error"', () => { - return cep({ nintendo: true, ps: false, xbox: false }).catch(error => { + return cep({ nintendo: true, ps: false, xbox: false }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { message: - 'Você deve chamar o construtor utilizando uma String ou um Number.', - service: 'cep_validation' - } - ] - }) - }) - }) - }) - - describe('when invoked with an Function', () => { + "Você deve chamar o construtor utilizando uma String ou um Number.", + service: "cep_validation", + }, + ], + }); + }); + }); + }); + + describe("when invoked with an Function", () => { it('should reject with "validation_error"', () => { return cep(function zelda() { - return 'link' - }).catch(error => { + return "link"; + }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { message: - 'Você deve chamar o construtor utilizando uma String ou um Number.', - service: 'cep_validation' - } - ] - }) - }) - }) - }) + "Você deve chamar o construtor utilizando uma String ou um Number.", + service: "cep_validation", + }, + ], + }); + }); + }); + }); describe('when invoked with a valid "05010000" String', () => { - it('should fulfill with correct address', () => { - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + it("should fulfill with correct address", () => { + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ) - - return cep('05010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: address.service + path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + ); + + return cep("05010000").then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: address.service, }) - ) - }) - }) - - describe('when invoked with a valid 5010000 Number', () => { - it('should fulfill with correct address', () => { - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + ); + }); + }); + + describe("when invoked with a valid 5010000 Number", () => { + it("should fulfill with correct address", () => { + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ) - - return cep(5010000) - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: address.service + path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + ); + + return cep(5010000).then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: address.service, }) - ) - }) - }) - - describe('Should succeed only with viacep service', () => { - it('should fulfill with correct address', () => { - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + ); + }); + }); + + describe("Should succeed only with viacep service", () => { + it("should fulfill with correct address", () => { + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/99999999') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/99999999") .replyWithFile( 404, - path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ) - - return cep('05010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'viacep' + path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + ); + + return cep("05010000").then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "viacep", }) - ) - }) - }) - - describe('Should succeed only with widenet service', () => { - it('should fulfill with correct address', () => { - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + ); + }); + }); + + describe("Should succeed only with widenet service", () => { + it("should fulfill with correct address", () => { + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/99999999') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/99999999") .replyWithFile( 404, - path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ) - - return cep('5010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'widenet' - })) - }) - }) - - describe('Should succeed only with brasilapi service', () => { - it('should fulfill with correct address', () => { - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + ); + + return cep("5010000").then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "widenet", + }) + ); + }); + }); + + describe("Should succeed only with brasilapi service", () => { + it("should fulfill with correct address", () => { + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ) - - return cep('5010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'brasilapi' - })) - }) - }) + path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + ); + + return cep("5010000").then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "brasilapi", + }) + ); + }); + }); describe('when invoked with an inexistent "99999999" CEP', () => { it('should reject with "service_error"', () => { - nock('https://viacep.com.br') - .get('/ws/99999999/json/') + nock("https://viacep.com.br") + .get("/ws/99999999/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/99999-999.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/99999-999.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/99999999') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/99999999") + .replyWithFile( + 404, + path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + ); + nock("https://api.postmon.com.br") + .get("/v1/cep/99999999") .replyWithFile( 404, - path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/postmon-cep-99999999-error.json") + ); - return cep('99999999').catch(error => { + return cep("99999999").catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Todos os serviços de CEP retornaram erro.', - type: 'service_error', + name: "CepPromiseError", + message: "Todos os serviços de CEP retornaram erro.", + type: "service_error", errors: [ { - message: 'CEP não encontrado na base do ViaCEP.', - service: 'viacep' + message: "CEP não encontrado na base do ViaCEP.", + service: "viacep", }, { - message: 'CEP não encontrado na base do WideNet.', - service: 'widenet' - } - ] - }) - }) - }) - }) + message: "CEP não encontrado na base do WideNet.", + service: "widenet", + }, + { + message: "CEP não encontrado na base do Postmon.", + service: "postmon", + }, + ], + }); + }); + }); + }); describe('when invoked with an invalid "123456789" CEP', () => { it('should reject with "validation_error"', () => { - return cep('123456789').catch(error => { + return cep("123456789").catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'CEP deve conter exatamente 8 caracteres.', - type: 'validation_error', + name: "CepPromiseError", + message: "CEP deve conter exatamente 8 caracteres.", + type: "validation_error", errors: [ { - service: 'cep_validation', - message: 'CEP informado possui mais do que 8 caracteres.' - } - ] - }) - }) - }) - }) - - describe('when http request fails both for all services with bad response', () => { - it('should reject with "service_error"', () => { - nock('https://viacep.com.br') - .get('/ws/05010000/json/') - .reply(400, '

Bad Request (400)

') - - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') - .reply(400, '

Bad Request (400)

') - - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') - .reply(400, '

Bad Request (400)

') + service: "cep_validation", + message: "CEP informado possui mais do que 8 caracteres.", + }, + ], + }); + }); + }); + }); - return cep('05010000').catch(error => { + describe("when http request fails both for all services with bad response", () => { + it('should reject with "service_error"', () => { + nock("https://viacep.com.br") + .get("/ws/05010000/json/") + .reply(400, "

Bad Request (400)

"); + + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") + .reply(400, "

Bad Request (400)

"); + + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") + .reply(400, "

Bad Request (400)

"); + nock("https://api.postmon.com.br") + .get("/v1/cep/05010000") + .reply(400, "

Bad Request (400)

"); + + return cep("05010000").catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Todos os serviços de CEP retornaram erro.', - type: 'service_error', + name: "CepPromiseError", + message: "Todos os serviços de CEP retornaram erro.", + type: "service_error", errors: [ { - message: 'Erro ao se conectar com o serviço ViaCEP.', - service: 'viacep' + message: "Erro ao se conectar com o serviço ViaCEP.", + service: "viacep", }, { - message: 'Erro ao se conectar com o serviço WideNet.', - service: 'widenet' + message: "Erro ao se conectar com o serviço WideNet.", + service: "widenet", }, { - name: 'ServiceError', - message: 'CEP não encontrado na base do BrasilAPI.', - service: 'brasilapi' - } - ] - }) - }) - }) - }) + message: "Erro ao se conectar com o serviço Postmon.", + service: "postmon", + }, + { + name: "ServiceError", + message: "CEP não encontrado na base do BrasilAPI.", + service: "brasilapi", + }, + ], + }); + }); + }); + }); afterEach(() => { - nock.cleanAll() - }) + nock.cleanAll(); + }); after(() => { - delete global.window - }) -}) + delete global.window; + }); +}); diff --git a/test/unit/cep-promise-node.spec.js b/test/unit/cep-promise-node.spec.js index 80911630..2e3a5a00 100644 --- a/test/unit/cep-promise-node.spec.js +++ b/test/unit/cep-promise-node.spec.js @@ -1,889 +1,904 @@ -'use strict' +"use strict"; -import chai from 'chai' -import chaiAsPromised from 'chai-as-promised' -import chaiSubset from 'chai-subset' -import nock from 'nock' -import path from 'path' +import chai from "chai"; +import chaiAsPromised from "chai-as-promised"; +import chaiSubset from "chai-subset"; +import nock from "nock"; +import path from "path"; -import cep from '../../src/cep-promise.js' -import CepPromiseError from '../../src/errors/cep-promise.js' +import cep from "../../src/cep-promise.js"; +import CepPromiseError from "../../src/errors/cep-promise.js"; -chai.use(chaiAsPromised) -chai.use(chaiSubset) +chai.use(chaiAsPromised); +chai.use(chaiSubset); -let expect = chai.expect +let expect = chai.expect; -describe('[unit] cep-promise for node', () => { +describe("[unit] cep-promise for node", () => { before(() => { - nock.disableNetConnect() - }) + nock.disableNetConnect(); + }); - describe('when imported', () => { - it('should return a Function', () => { - expect(cep).to.be.a('function') - }) - }) + describe("when imported", () => { + it("should return a Function", () => { + expect(cep).to.be.a("function"); + }); + }); - describe('when invoked', () => { - it('should return a Promise', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("when invoked", () => { + it("should return a Promise", () => { + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + ); + nock("https://api.postmon.com.br") + .get("/v1/cep/05010000") + .replyWithFile( + 200, + path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + ); - const cepPromise = cep('05010000') - expect(cepPromise.then).to.be.a('function') - expect(cepPromise.catch).to.be.a('function') - }) - }) + const cepPromise = cep("05010000"); + expect(cepPromise.then).to.be.a("function"); + expect(cepPromise.catch).to.be.a("function"); + }); + }); - describe('when invoked without arguments', () => { + describe("when invoked without arguments", () => { it('should reject with "validation_error"', () => { - return cep().catch(error => { + return cep().catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { message: - 'Você deve chamar o construtor utilizando uma String ou um Number.', - service: 'cep_validation' - } - ] - }) - }) - }) - }) - - describe('when invoked with an Array', () => { + "Você deve chamar o construtor utilizando uma String ou um Number.", + service: "cep_validation", + }, + ], + }); + }); + }); + }); + + describe("when invoked with an Array", () => { it('should reject with "validation_error"', () => { - return cep([1, 2, 3]).catch(error => { + return cep([1, 2, 3]).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { message: - 'Você deve chamar o construtor utilizando uma String ou um Number.', - service: 'cep_validation' - } - ] - }) - }) - }) - }) - - describe('when invoked with an Object', () => { + "Você deve chamar o construtor utilizando uma String ou um Number.", + service: "cep_validation", + }, + ], + }); + }); + }); + }); + + describe("when invoked with an Object", () => { it('should reject with "validation_error"', () => { - return cep({ nintendo: true, ps: false, xbox: false }).catch(error => { + return cep({ nintendo: true, ps: false, xbox: false }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { message: - 'Você deve chamar o construtor utilizando uma String ou um Number.', - service: 'cep_validation' - } - ] - }) - }) - }) - }) - - describe('when invoked with an Function', () => { + "Você deve chamar o construtor utilizando uma String ou um Number.", + service: "cep_validation", + }, + ], + }); + }); + }); + }); + + describe("when invoked with an Function", () => { it('should reject with "validation_error"', () => { return cep(function zelda() { - return 'link' - }).catch(error => { + return "link"; + }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { message: - 'Você deve chamar o construtor utilizando uma String ou um Number.', - service: 'cep_validation' - } - ] - }) - }) - }) - }) + "Você deve chamar o construtor utilizando uma String ou um Number.", + service: "cep_validation", + }, + ], + }); + }); + }); + }); describe('when invoked with a valid "05010000" String', () => { - it('should fulfill with correct address', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + it("should fulfill with correct address", () => { + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + ); - return cep('05010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: address.service + return cep("05010000").then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: address.service, }) - ) - }) - }) + ); + }); + }); - describe('when invoked with a valid 5010000 Number', () => { - it('should fulfill with correct address', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("when invoked with a valid 5010000 Number", () => { + it("should fulfill with correct address", () => { + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + ); - return cep(5010000) - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: address.service + return cep(5010000).then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: address.service, }) - ) - }) - }) + ); + }); + }); - describe('Should succeed only with correios service', () => { - it('should fulfill with correct address', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("Should succeed only with correios service", () => { + it("should fulfill with correct address", () => { + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-99999999-error.json") + ); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + ); - nock('https://cep.widenet.host') - .get('/file/apicep/05010-000.json') + nock("https://cep.widenet.host") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/99999999') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/99999999") .replyWithFile( 404, - path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ) - - - return cep('05010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'correios' - }) - ) - }) - }) - - describe('Should succeed only with correios-alt service', () => { - it('should fulfill with correct address', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + ); + + return cep("05010000").then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "correios", + }) + ); + }); + }); + + describe("Should succeed only with correios-alt service", () => { + it("should fulfill with correct address", () => { + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 500, - path.join(__dirname, '/fixtures/response-unknown-format.xml') - ) + path.join(__dirname, "/fixtures/response-unknown-format.xml") + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/99999999') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithFile( 404, - path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ) - - - return cep('05010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'correios-alt' - }) - ) - }) - }) + path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + ); - describe('Should succeed only with viacep service', () => { - it('should fulfill with correct address', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + nock("https://api.postmon.com.br") + .get("/v1/cep/05010000") + .replyWithFile( + 404, + path.join(__dirname, "/fixtures/postmon-cep-99999999-error.json") + ); + + return cep("05010000").then((address) => { + expect(address) + .to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "correios-alt", + }); + }); + }); + }); + + describe("Should succeed only with viacep service", () => { + it("should fulfill with correct address", () => { + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 500, - path.join(__dirname, '/fixtures/response-unknown-format.xml') - ) + path.join(__dirname, "/fixtures/response-unknown-format.xml") + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-99999999-error.json") + ); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/99999999') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/99999999") .replyWithFile( 404, - path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ) - - return cep('05010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'viacep' + path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + ); + + return cep("05010000").then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "viacep", }) - ) - }) - }) + ); + }); + }); - describe('Should succeed only with widenet service', () => { - it('should fulfill with correct address', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("Should succeed only with widenet service", () => { + it("should fulfill with correct address", () => { + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 500, - path.join(__dirname, '/fixtures/response-unknown-format.xml') - ) + path.join(__dirname, "/fixtures/response-unknown-format.xml") + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-99999999-error.json") + ); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/99999999') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/99999999") .replyWithFile( 404, - path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ) - - return cep('5010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'widenet' - })) - }) - }) - - describe('Should succeed only with brasilapi service', () => { - it('should fulfill with correct address', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + ); + + return cep("5010000").then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "widenet", + }) + ); + }); + }); + + describe("Should succeed only with brasilapi service", () => { + it("should fulfill with correct address", () => { + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 500, - path.join(__dirname, '/fixtures/response-unknown-format.xml') - ) + path.join(__dirname, "/fixtures/response-unknown-format.xml") + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-99999999-error.json") + ); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + ); - return cep('5010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'brasilapi' - })) - }) - }) + return cep("5010000").then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "brasilapi", + }) + ); + }); + }); - describe('when its not possible to parse the returned XML and then succeed to one failover service', () => { - it('should fulfill with correct address', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("when its not possible to parse the returned XML and then succeed to one failover service", () => { + it("should fulfill with correct address", () => { + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-bad-xml.xml') - ) + path.join(__dirname, "/fixtures/response-bad-xml.xml") + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + ); - return cep('5010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: address.service - })) - }) - }) - - describe('when http request to Correios fails and then succeed to the failover service', () => { - it('should fulfill with correct address', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + return cep("5010000").then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: address.service, + }) + ); + }); + }); + + describe("when http request to Correios fails and then succeed to the failover service", () => { + it("should fulfill with correct address", () => { + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithError( - 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ) + "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + ); - return cep('5010000') - .then(address => expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: address.service - })) - }) - }) + return cep("5010000").then((address) => + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: address.service, + }) + ); + }); + }); describe('when invoked with an inexistent "99999999" CEP', () => { it('should reject with "service_error"', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 500, - path.join(__dirname, '/fixtures/response-cep-not-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-not-found.xml") + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-99999999-error.json") + ); - nock('https://viacep.com.br') - .get('/ws/99999999/json/') + nock("https://viacep.com.br") + .get("/ws/99999999/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + ); - nock('https://postmon.com.br') - .get('/v1/cep/05010000') + nock("https://api.postmon.com.br") + .get("/v1/cep/99999999") .replyWithFile( - 200, - path.join(__dirname, '/fixtures/postmon-cep-99999999-error.json') - ) - + 404, + path.join(__dirname, "/fixtures/postmon-cep-99999999-error.json") + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/99999-999.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/99999-999.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/99999999') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/99999999") .replyWithFile( 404, - path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ) + path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + ); - return cep('99999999').catch(error => { + return cep("99999999").catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Todos os serviços de CEP retornaram erro.', - type: 'service_error', + name: "CepPromiseError", + message: "Todos os serviços de CEP retornaram erro.", + type: "service_error", errors: [ { - message: 'CEP NAO ENCONTRADO', - service: 'correios' + message: "CEP NAO ENCONTRADO", + service: "correios", }, { - message: 'CEP não encontrado na base dos Correios.', - service: 'correios-alt' + message: "CEP não encontrado na base dos Correios.", + service: "correios-alt", }, { - message: 'CEP não encontrado na base do ViaCEP.', - service: 'viacep' + message: "CEP não encontrado na base do ViaCEP.", + service: "viacep", }, { - message: 'CEP não encontrado na base do WideNet.', - service: 'widenet' + message: "CEP não encontrado na base do WideNet.", + service: "widenet", }, { - message: 'CEP não encontrado na base do postmon.', - service: 'postmon' - } - ] - }) - }) - }) - }) + message: "CEP não encontrado na base do Postmon.", + service: "postmon", + }, + ], + }); + }); + }); + }); describe('when invoked with an invalid "123456789" CEP', () => { it('should reject with "validation_error"', () => { - return cep('123456789').catch(error => { + return cep("123456789").catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'CEP deve conter exatamente 8 caracteres.', - type: 'validation_error', + name: "CepPromiseError", + message: "CEP deve conter exatamente 8 caracteres.", + type: "validation_error", errors: [ { - service: 'cep_validation', - message: 'CEP informado possui mais do que 8 caracteres.' - } - ] - }) - }) - }) - }) - - describe('when http request fails both for primary and secondary service with bad response', () => { + service: "cep_validation", + message: "CEP informado possui mais do que 8 caracteres.", + }, + ], + }); + }); + }); + }); + + describe("when http request fails both for primary and secondary service with bad response", () => { it('should reject with "service_error"', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithError( - 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ) + "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') - .reply(400, '

Bad Request (400)

') + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") + .reply(400, "

Bad Request (400)

"); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') - .reply(400, '

Bad Request (400)

') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") + .reply(400, "

Bad Request (400)

"); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') - .reply(400, '

Bad Request (400)

') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") + .reply(400, "

Bad Request (400)

"); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') - .reply(400, '

Bad Request (400)

') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") + .reply(400, "

Bad Request (400)

"); - return cep('05010000').catch(error => { + return cep("05010000").catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Todos os serviços de CEP retornaram erro.', - type: 'service_error', + name: "CepPromiseError", + message: "Todos os serviços de CEP retornaram erro.", + type: "service_error", errors: [ { - message: 'Erro ao se conectar com o serviço dos Correios.', - service: 'correios' + message: "Erro ao se conectar com o serviço dos Correios.", + service: "correios", }, { - message: 'Erro ao se conectar com o serviço dos Correios Alt.', - service: 'correios-alt' + message: "Erro ao se conectar com o serviço dos Correios Alt.", + service: "correios-alt", }, { - message: 'Erro ao se conectar com o serviço ViaCEP.', - service: 'viacep' + message: "Erro ao se conectar com o serviço ViaCEP.", + service: "viacep", }, { - message: 'Erro ao se conectar com o serviço WideNet.', - service: 'widenet' + message: "Erro ao se conectar com o serviço WideNet.", + service: "widenet", }, { - name: 'ServiceError', - message: 'CEP não encontrado na base do BrasilAPI.', - service: 'brasilapi' - } - ] - }) - }) - }) - }) - - describe('when http request has unformatted xml and alternatives services fails', () => { + name: "ServiceError", + message: "CEP não encontrado na base do BrasilAPI.", + service: "brasilapi", + }, + ], + }); + }); + }); + }); + + describe("when http request has unformatted xml and alternatives services fails", () => { it('should reject with "service_error"', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-bad-xml.xml') - ) + path.join(__dirname, "/fixtures/response-bad-xml.xml") + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') - .reply(200, {erro:true}) + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") + .reply(200, { erro: true }); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') - .reply(400, '

Bad Request (400)

') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") + .reply(400, "

Bad Request (400)

"); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') - .reply(400, '

Bad Request (400)

') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") + .reply(400, "

Bad Request (400)

"); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') - .reply(400, '

Bad Request (400)

') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") + .reply(400, "

Bad Request (400)

"); - return cep('05010000').catch(error => { + return cep("05010000").catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Todos os serviços de CEP retornaram erro.', - type: 'service_error', + name: "CepPromiseError", + message: "Todos os serviços de CEP retornaram erro.", + type: "service_error", errors: [ { - message: 'Não foi possível interpretar o XML de resposta.', - service: 'correios' + message: "Não foi possível interpretar o XML de resposta.", + service: "correios", }, { - message: 'CEP não encontrado na base dos Correios.', - service: 'correios-alt' + message: "CEP não encontrado na base dos Correios.", + service: "correios-alt", }, { - message: 'Erro ao se conectar com o serviço ViaCEP.', - service: 'viacep' + message: "Erro ao se conectar com o serviço ViaCEP.", + service: "viacep", }, { - message: 'Erro ao se conectar com o serviço WideNet.', - service: 'widenet' + message: "Erro ao se conectar com o serviço WideNet.", + service: "widenet", }, { - name: 'ServiceError', - message: 'CEP não encontrado na base do BrasilAPI.', - service: 'brasilapi' - } - ] - }) - }) - }) - }) - - describe('when http request fails both for primary and secondary service with error', () => { + name: "ServiceError", + message: "CEP não encontrado na base do BrasilAPI.", + service: "brasilapi", + }, + ], + }); + }); + }); + }); + + describe("when http request fails both for primary and secondary service with error", () => { it('should reject with "service_error"', () => { - nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithError( - 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ) + "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + ); - nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') - .reply(200, {erro:true}) + nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") + .reply(200, { erro: true }); - nock('https://viacep.com.br') - .get('/ws/05010000/json/') + nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithError( - 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ) + "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + ); - nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithError( - 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ) + "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + ); - nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") .replyWithError( - 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ) + "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + ); - return cep('05010000').catch(error => { + return cep("05010000").catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Todos os serviços de CEP retornaram erro.', - type: 'service_error', + name: "CepPromiseError", + message: "Todos os serviços de CEP retornaram erro.", + type: "service_error", errors: [ { - message: 'Erro ao se conectar com o serviço dos Correios.', - service: 'correios' + message: "Erro ao se conectar com o serviço dos Correios.", + service: "correios", }, { - message: 'CEP não encontrado na base dos Correios.', - service: 'correios-alt' + message: "CEP não encontrado na base dos Correios.", + service: "correios-alt", }, { - message: 'Erro ao se conectar com o serviço ViaCEP.', - service: 'viacep' + message: "Erro ao se conectar com o serviço ViaCEP.", + service: "viacep", }, { - message: 'Erro ao se conectar com o serviço WideNet.', - service: 'widenet' + message: "Erro ao se conectar com o serviço WideNet.", + service: "widenet", }, { - message: 'Erro ao se conectar com o serviço BrasilAPI.', - service: 'brasilapi' - } - ] - }) - }) - }) - }) + message: "Erro ao se conectar com o serviço BrasilAPI.", + service: "brasilapi", + }, + ], + }); + }); + }); + }); afterEach(() => { - nock.cleanAll() - }) -}) + nock.cleanAll(); + }); +}); diff --git a/test/unit/cep-promise-providers.spec.js b/test/unit/cep-promise-providers.spec.js index ae0ea9f4..ece7fc57 100644 --- a/test/unit/cep-promise-providers.spec.js +++ b/test/unit/cep-promise-providers.spec.js @@ -1,541 +1,582 @@ -'use strict' +"use strict"; -import chai from 'chai' -import chaiSubset from 'chai-subset' -import nock from 'nock' -import path from 'path' +import chai from "chai"; +import chaiSubset from "chai-subset"; +import nock from "nock"; +import path from "path"; -import cep from '../../src/cep-promise.js' -import CepPromiseError from '../../src/errors/cep-promise.js' -import { getAvailableServices } from '../../src/services/index.js' +import cep from "../../src/cep-promise.js"; +import CepPromiseError from "../../src/errors/cep-promise.js"; +import { getAvailableServices } from "../../src/services/index.js"; -chai.use(chaiSubset) +chai.use(chaiSubset); -let expect = chai.expect +let expect = chai.expect; -describe('when invoked with providers parameter', () => { +describe("when invoked with providers parameter", () => { before(() => { - nock.disableNetConnect() - }) + nock.disableNetConnect(); + }); - describe('and the providers param is a string', () => { + describe("and the providers param is a string", () => { it('should reject with "validation_error"', () => { - return cep('05010000', { providers: 'viacep' }).catch(error => { + return cep("05010000", { providers: "viacep" }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { - service: 'providers_validation', - message: 'O parâmetro providers deve ser uma lista.' - } - ] - }) - }) - }) - }) - - describe('and the providers param is a integer', () => { + service: "providers_validation", + message: "O parâmetro providers deve ser uma lista.", + }, + ], + }); + }); + }); + }); + + describe("and the providers param is a integer", () => { it('should reject with "validation_error"', () => { - return cep('05010000', { providers: 123 }).catch(error => { + return cep("05010000", { providers: 123 }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { - service: 'providers_validation', - message: 'O parâmetro providers deve ser uma lista.' - } - ] - }) - }) - }) - }) - - describe('and the providers param is a object', () => { + service: "providers_validation", + message: "O parâmetro providers deve ser uma lista.", + }, + ], + }); + }); + }); + }); + + describe("and the providers param is a object", () => { it('should reject with "validation_error"', () => { - return cep('05010000', { providers: {} }).catch(error => { + return cep("05010000", { providers: {} }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { - service: 'providers_validation', - message: 'O parâmetro providers deve ser uma lista.' - } - ] - }) - }) - }) - }) - - describe('and the providers param is a function', () => { + service: "providers_validation", + message: "O parâmetro providers deve ser uma lista.", + }, + ], + }); + }); + }); + }); + + describe("and the providers param is a function", () => { it('should reject with "validation_error"', () => { - return cep('05010000', { providers: () => () => { } }).catch(error => { + return cep("05010000", { providers: () => () => {} }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: 'CepPromiseError', - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + name: "CepPromiseError", + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { - service: 'providers_validation', - message: 'O parâmetro providers deve ser uma lista.' - } - ] - }) - }) - }) - }) - - describe('and the providers param is a invalid array', () => { + service: "providers_validation", + message: "O parâmetro providers deve ser uma lista.", + }, + ], + }); + }); + }); + }); + + describe("and the providers param is a invalid array", () => { it('should reject with "validation_error"', () => { - const availableProviders = Object.keys(getAvailableServices()) + const availableProviders = Object.keys(getAvailableServices()); - return cep('05010000', { providers: [123, 'viacep'] }).catch(error => { + return cep("05010000", { providers: [123, "viacep"] }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - message: 'Erro ao inicializar a instância do CepPromise.', - type: 'validation_error', + message: "Erro ao inicializar a instância do CepPromise.", + type: "validation_error", errors: [ { - message: - `O provider "123" é inválido. Os providers disponíveis são: ["${availableProviders.join('", "')}"].`, - service: 'providers_validation' - } - ] - }) - }) - }) - }) + message: `O provider "123" é inválido. Os providers disponíveis são: ["${availableProviders.join( + '", "' + )}"].`, + service: "providers_validation", + }, + ], + }); + }); + }); + }); - describe('and the providers param is [\'viacep\']', () => { - it('should call only viacep service', () => { - const correiosMock = nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("and the providers param is ['viacep']", () => { + it("should call only viacep service", () => { + const correiosMock = nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); - const correiosAltMock = nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + const correiosAltMock = nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - const viaCepMock = nock('https://viacep.com.br') - .get('/ws/05010000/json/') + const viaCepMock = nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) - const postmonMock = nock('https://postmon.com.br') - .get('/v1/cep/05010000') + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); + const postmonMock = nock("https://api.postmon.com.br") + .get("/v1/cep/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + ); - const wideNetMock = nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + const wideNetMock = nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - return cep('05010000', { providers: ['viacep'] }) - .then(address => { - expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'viacep' - }) + return cep("05010000", { providers: ["viacep"] }).then((address) => { + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "viacep", + }); - expect(viaCepMock.isDone()).to.be.equal(true) - expect(correiosMock.isDone()).to.be.equal(false) - expect(correiosAltMock.isDone()).to.be.equal(false) - expect(wideNetMock.isDone()).to.be.equal(false) - expect(postmonMock.isDone()).to.be.equal(false) - }) - }) - }) + expect(viaCepMock.isDone()).to.be.equal(true); + expect(correiosMock.isDone()).to.be.equal(false); + expect(correiosAltMock.isDone()).to.be.equal(false); + expect(wideNetMock.isDone()).to.be.equal(false); + expect(postmonMock.isDone()).to.be.equal(false); + }); + }); + }); - describe('and the providers param is [\'postmon\']', () => { - it('should call only postmon service', () => { - const correiosMock = nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("and the providers param is ['postmon']", () => { + it("should call only postmon service", () => { + const correiosMock = nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); - const correiosAltMock = nock('https://buscacepinter.correios.com.br') - .post('/app/cep/carrega-cep.php') + const correiosAltMock = nock("https://buscacepinter.correios.com.br") + .post("/app/cep/carrega-cep.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - const viaCepMock = nock('https://viacep.com.br') - .get('/ws/05010000/json/') + const viaCepMock = nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) - const postmonMock = nock('https://postmon.com.br') - .get('/v1/cep/05010000') + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); + const postmonMock = nock("https://api.postmon.com.br") + .get("/v1/cep/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + ); - const wideNetMock = nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + const wideNetMock = nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - return cep('05010000', { providers: ['postmon'] }) - .then(address => { - console.log(address); - expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'postmon' - }) + return cep("05010000", { providers: ["postmon"] }).then((address) => { + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "postmon", + }); - // expect(viaCepMock.isDone()).to.be.equal(false) - // expect(correiosMock.isDone()).to.be.equal(false) - // expect(correiosAltMock.isDone()).to.be.equal(false) - // expect(wideNetMock.isDone()).to.be.equal(false) - // expect(postmonMock.isDone()).to.be.equal(true) - }) - }) - }) + expect(viaCepMock.isDone()).to.be.equal(false); + expect(correiosMock.isDone()).to.be.equal(false); + expect(correiosAltMock.isDone()).to.be.equal(false); + expect(wideNetMock.isDone()).to.be.equal(false); + expect(postmonMock.isDone()).to.be.equal(true); + }); + }); + }); - describe('and the providers param is [\'widenet\']', () => { - it('should call only widenet service', () => { - const correiosMock = nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("and the providers param is ['widenet']", () => { + it("should call only widenet service", () => { + const correiosMock = nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); - const correiosAltMock = nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + const correiosAltMock = nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - const viaCepMock = nock('https://viacep.com.br') - .get('/ws/05010000/json/') + const viaCepMock = nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - const wideNetMock = nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + const wideNetMock = nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") + .replyWithFile( + 200, + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); + const postmonMock = nock("https://api.postmon.com.br") + .get("/v1/cep/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + ); - return cep('05010000', { providers: ['widenet'] }) - .then(address => { - expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'widenet' - }) + return cep("05010000", { providers: ["widenet"] }).then((address) => { + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "widenet", + }); - expect(wideNetMock.isDone()).to.be.equal(true) - expect(viaCepMock.isDone()).to.be.equal(false) - expect(correiosMock.isDone()).to.be.equal(false) - expect(correiosAltMock.isDone()).to.be.equal(false) - }) - }) - }) + expect(wideNetMock.isDone()).to.be.equal(true); + expect(viaCepMock.isDone()).to.be.equal(false); + expect(correiosMock.isDone()).to.be.equal(false); + expect(correiosAltMock.isDone()).to.be.equal(false); + expect(postmonMock.isDone()).to.be.equal(false); + }); + }); + }); - describe('and the providers param is [\'correios\']', () => { - it('should call only correios service', () => { - const correiosMock = nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("and the providers param is ['correios']", () => { + it("should call only correios service", () => { + const correiosMock = nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); + const postmonMock = nock("https://api.postmon.com.br") + .get("/v1/cep/05010000") + .replyWithFile( + 200, + path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + ); - const correiosAltMock = nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + const correiosAltMock = nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - const viaCepMock = nock('https://viacep.com.br') - .get('/ws/05010000/json/') + const viaCepMock = nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - const wideNetMock = nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + const wideNetMock = nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - return cep('05010000', { providers: ['correios'] }) - .then(address => { - expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'correios' - }) + return cep("05010000", { providers: ["correios"] }).then((address) => { + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "correios", + }); - expect(correiosMock.isDone()).to.be.equal(true) - expect(correiosAltMock.isDone()).to.be.equal(false) - expect(viaCepMock.isDone()).to.be.equal(false) - expect(wideNetMock.isDone()).to.be.equal(false) - }) - }) - }) + expect(correiosMock.isDone()).to.be.equal(true); + expect(correiosAltMock.isDone()).to.be.equal(false); + expect(viaCepMock.isDone()).to.be.equal(false); + expect(wideNetMock.isDone()).to.be.equal(false); + expect(postmonMock.isDone()).to.be.equal(false); + }); + }); + }); - describe('and the providers param is [\'correios-alt\']', () => { - it('should call only correios service', () => { - const correiosMock = nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("and the providers param is ['correios-alt']", () => { + it("should call only correios alt service", () => { + const correiosMock = nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); + const postmonMock = nock("https://api.postmon.com.br") + .get("/v1/cep/05010000") + .replyWithFile( + 200, + path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + ); - const correiosAltMock = nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + const correiosAltMock = nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - const viaCepMock = nock('https://viacep.com.br') - .get('/ws/05010000/json/') + const viaCepMock = nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - const wideNetMock = nock('https://cep.widenet.host') - .get('/file/apicep/05010-000.json') + const wideNetMock = nock("https://cep.widenet.host") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - return cep('05010000', { providers: ['correios-alt']}) - .then(address => { + return cep("05010000", { providers: ["correios-alt"] }).then( + (address) => { expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'correios-alt' - }) + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "correios-alt", + }); - expect(correiosMock.isDone()).to.be.equal(false) - expect(correiosAltMock.isDone()).to.be.equal(true) - expect(viaCepMock.isDone()).to.be.equal(false) - expect(wideNetMock.isDone()).to.be.equal(false) - }) - }) - }) + expect(correiosMock.isDone()).to.be.equal(false); + expect(correiosAltMock.isDone()).to.be.equal(true); + expect(viaCepMock.isDone()).to.be.equal(false); + expect(wideNetMock.isDone()).to.be.equal(false); + expect(postmonMock.isDone()).to.be.equal(false); + } + ); + }); + }); - describe('and the providers param is [\'brasilapi\']', () => { - it('should call only brasilapi service', () => { - const correiosMock = nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("and the providers param is ['brasilapi']", () => { + it("should call only brasilapi service", () => { + const correiosMock = nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); - const correiosAltMock = nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + const correiosAltMock = nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - const viaCepMock = nock('https://viacep.com.br') - .get('/ws/05010000/json/') + const postmonMock = nock("https://api.postmon.com.br") + .get("/v1/cep/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + ); - const wideNetMock = nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + const viaCepMock = nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - const brasilAPIMock = nock('https://brasilapi.com.br/') - .get('/api/cep/v1/05010000') + const wideNetMock = nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - return cep('05010000', { providers: ['brasilapi'] }) - .then(address => { - expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: 'brasilapi' - }) + const brasilAPIMock = nock("https://brasilapi.com.br/") + .get("/api/cep/v1/05010000") + .replyWithFile( + 200, + path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + ); + + return cep("05010000", { providers: ["brasilapi"] }).then((address) => { + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: "brasilapi", + }); - expect(correiosMock.isDone()).to.be.equal(false) - expect(correiosAltMock.isDone()).to.be.equal(false) - expect(viaCepMock.isDone()).to.be.equal(false) - expect(wideNetMock.isDone()).to.be.equal(false) - expect(brasilAPIMock.isDone()).to.be.equal(true) - }) - }) - }) + expect(correiosMock.isDone()).to.be.equal(false); + expect(correiosAltMock.isDone()).to.be.equal(false); + expect(viaCepMock.isDone()).to.be.equal(false); + expect(wideNetMock.isDone()).to.be.equal(false); + expect(postmonMock.isDone()).to.be.equal(false); + expect(brasilAPIMock.isDone()).to.be.equal(true); + }); + }); + }); + + describe("and the providers param is ['correios, viacep']", () => { + it("should call only correios and viacep services", () => { + const correiosMock = nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + .replyWithFile( + 200, + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); - describe('and the providers param is [\'correios, viacep\']', () => { - it('should call only correios and viacep services', () => { - const correiosMock = nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + const correiosAltMock = nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - const correiosAltMock = nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + const viaCepMock = nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - const viaCepMock = nock('https://viacep.com.br') - .get('/ws/05010000/json/') + const wideNetMock = nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); - const wideNetMock = nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + const postmonMock = nock("https://api.postmon.com.br") + .get("/v1/cep/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + ); - return cep('05010000', { providers: ['correios', 'viacep'] }) - .then(address => { + return cep("05010000", { providers: ["correios", "viacep"] }).then( + (address) => { expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: address.service - }) + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: address.service, + }); - expect(viaCepMock.isDone()).to.be.equal(true) - expect(correiosMock.isDone()).to.be.equal(true) - expect(correiosAltMock.isDone()).to.be.equal(false) - expect(wideNetMock.isDone()).to.be.equal(false) - }) - }) - }) + expect(viaCepMock.isDone()).to.be.equal(true); + expect(correiosMock.isDone()).to.be.equal(true); + expect(correiosAltMock.isDone()).to.be.equal(false); + expect(wideNetMock.isDone()).to.be.equal(false); + expect(postmonMock.isDone()).to.be.equal(false); + } + ); + }); + }); - describe('and the providers param is []', () => { - it('should call all services', () => { - const correiosMock = nock('https://apps.correios.com.br') - .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') + describe("and the providers param is []", () => { + it("should call all services", () => { + const correiosMock = nock("https://apps.correios.com.br") + .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") .replyWithFile( 200, - path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ) + path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + ); - const correiosAltMock = nock('https://buscacepinter.correios.com.br') - .post('/app/endereco/carrega-cep-endereco.php') + const correiosAltMock = nock("https://buscacepinter.correios.com.br") + .post("/app/endereco/carrega-cep-endereco.php") .replyWithFile( 200, - path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + ); - const viaCepMock = nock('https://viacep.com.br') - .get('/ws/05010000/json/') + const postmonMock = nock("https://api.postmon.com.br") + .get("/v1/cep/05010000") .replyWithFile( 200, - path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + ); - const wideNetMock = nock('https://cdn.apicep.com') - .get('/file/apicep/05010-000.json') + const viaCepMock = nock("https://viacep.com.br") + .get("/ws/05010000/json/") .replyWithFile( 200, - path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ) + path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + ); - return cep('05010000', { providers: [] }) - .then(address => { - expect(address).to.deep.equal({ - cep: '05010000', - state: 'SP', - city: 'São Paulo', - neighborhood: 'Perdizes', - street: 'Rua Caiubi', - service: address.service - }) - - expect(viaCepMock.isDone()).to.be.equal(true) - expect(correiosMock.isDone()).to.be.equal(true) - expect(correiosAltMock.isDone()).to.be.equal(true) - expect(wideNetMock.isDone()).to.be.equal(true) - }) - }) - }) + const wideNetMock = nock("https://cdn.apicep.com") + .get("/file/apicep/05010-000.json") + .replyWithFile( + 200, + path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + ); + + return cep("05010000", { providers: [] }).then((address) => { + expect(address).to.deep.equal({ + cep: "05010000", + state: "SP", + city: "São Paulo", + neighborhood: "Perdizes", + street: "Rua Caiubi", + service: address.service, + }); + + expect(viaCepMock.isDone()).to.be.equal(true); + expect(correiosMock.isDone()).to.be.equal(true); + expect(correiosAltMock.isDone()).to.be.equal(true); + expect(wideNetMock.isDone()).to.be.equal(true); + expect(postmonMock.isDone()).to.be.equal(true); + }); + }); + }); afterEach(() => { - nock.cleanAll() - }) -}) + nock.cleanAll(); + }); +}); diff --git a/test/unit/fixtures/postmon-cep-05010000-found.json b/test/unit/fixtures/postmon-cep-05010000-found.json index 0805018a..ae0d955b 100644 --- a/test/unit/fixtures/postmon-cep-05010000-found.json +++ b/test/unit/fixtures/postmon-cep-05010000-found.json @@ -1,11 +1,11 @@ { "bairro": "Perdizes", - "cidade": "S\u00e3o Paulo", + "cidade": "São Paulo", "logradouro": "Rua Caiubi", "estado_info": { "area_km2": "248.221,996", "codigo_ibge": "35", - "nome": "S\u00e3o Paulo" + "nome": "São Paulo" }, "cep": "05010000", "cidade_info": { "area_km2": "1521,11", "codigo_ibge": "3550308" }, From d5ccc8e539ceaf30f8cf34e36f31ec662c182c5a Mon Sep 17 00:00:00 2001 From: Rodrigo Teixeira Andreotti Date: Thu, 28 Mar 2024 18:58:18 -0300 Subject: [PATCH 07/10] Rollback quotes --- test/e2e/cep-promise.spec.js | 98 +-- test/unit/cep-promise-browser.spec.js | 402 ++++++------ test/unit/cep-promise-node.spec.js | 826 ++++++++++++------------ test/unit/cep-promise-providers.spec.js | 486 +++++++------- test/unit/cep-promise-timeout.spec.js | 2 +- 5 files changed, 907 insertions(+), 907 deletions(-) diff --git a/test/e2e/cep-promise.spec.js b/test/e2e/cep-promise.spec.js index a9732dd3..6b416601 100644 --- a/test/e2e/cep-promise.spec.js +++ b/test/e2e/cep-promise.spec.js @@ -1,85 +1,85 @@ -"use strict"; +'use strict'; -import chai from "chai"; -import chaiAsPromised from "chai-as-promised"; -import chaiSubset from "chai-subset"; -import nock from "nock"; +import chai from 'chai'; +import chaiAsPromised from 'chai-as-promised'; +import chaiSubset from 'chai-subset'; +import nock from 'nock'; -import cep from "../../src/cep-promise.js"; -import CepPromiseError from "../../src/errors/cep-promise.js"; +import cep from '../../src/cep-promise.js'; +import CepPromiseError from '../../src/errors/cep-promise.js'; chai.use(chaiAsPromised); chai.use(chaiSubset); let expect = chai.expect; -describe("[e2e] cep-promise", () => { +describe('[e2e] cep-promise', () => { before(() => { nock.enableNetConnect(); }); - describe('when invoked with a valid "05010000" string', () => { - it("should fulfill with correct address", () => - cep("05010000").then((address) => { + describe('when invoked with a valid '05010000' string', () => { + it('should fulfill with correct address', () => + cep('05010000').then((address) => { expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', service: address.service, }); })); }); - describe("when invoked with a valid 05010000 number", () => { - it("should fulfill with correct address", async () => { + describe('when invoked with a valid 05010000 number', () => { + it('should fulfill with correct address', async () => { const address = await cep(5010000); expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', service: address.service, }); }); }); - describe('when invoked with an inexistent "99999999" CEP', () => { - it('should reject with "service_error"', () => { - return cep("99999999").catch((error) => { + describe('when invoked with an inexistent '99999999' CEP', () => { + it('should reject with 'service_error'', () => { + return cep('99999999').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Todos os serviços de CEP retornaram erro.", - type: "service_error", + name: 'CepPromiseError', + message: 'Todos os serviços de CEP retornaram erro.', + type: 'service_error', errors: [ { - message: "CEP INVÁLIDO", - service: "correios", + message: 'CEP INVÁLIDO', + service: 'correios', }, { - message: "Erro ao se conectar com o serviço dos Correios Alt.", - service: "correios-alt", + message: 'Erro ao se conectar com o serviço dos Correios Alt.', + service: 'correios-alt', }, { - message: "CEP não encontrado na base do ViaCEP.", - service: "viacep", + message: 'CEP não encontrado na base do ViaCEP.', + service: 'viacep', }, { - service: "widenet", + service: 'widenet', }, { - message: "CEP não encontrado na base do Postmon.", - service: "postmon", + message: 'CEP não encontrado na base do Postmon.', + service: 'postmon', }, { - name: "ServiceError", - message: "CEP não encontrado na base do BrasilAPI.", - service: "brasilapi", + name: 'ServiceError', + message: 'CEP não encontrado na base do BrasilAPI.', + service: 'brasilapi', }, ], }); @@ -87,19 +87,19 @@ describe("[e2e] cep-promise", () => { }); }); - describe('when invoked with an invalid "123456789" CEP', () => { - it('should reject with "validation_error"', () => { - return cep("123456789").catch((error) => { + describe('when invoked with an invalid '123456789' CEP', () => { + it('should reject with 'validation_error'', () => { + return cep('123456789').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "CEP deve conter exatamente 8 caracteres.", - type: "validation_error", + name: 'CepPromiseError', + message: 'CEP deve conter exatamente 8 caracteres.', + type: 'validation_error', errors: [ { - service: "cep_validation", - message: "CEP informado possui mais do que 8 caracteres.", + service: 'cep_validation', + message: 'CEP informado possui mais do que 8 caracteres.', }, ], }); diff --git a/test/unit/cep-promise-browser.spec.js b/test/unit/cep-promise-browser.spec.js index 69d2ab31..4f818d0b 100644 --- a/test/unit/cep-promise-browser.spec.js +++ b/test/unit/cep-promise-browser.spec.js @@ -1,75 +1,75 @@ -"use strict"; +'use strict'; -import chai from "chai"; -import chaiAsPromised from "chai-as-promised"; -import chaiSubset from "chai-subset"; -import nock from "nock"; -import path from "path"; +import chai from 'chai'; +import chaiAsPromised from 'chai-as-promised'; +import chaiSubset from 'chai-subset'; +import nock from 'nock'; +import path from 'path'; -import cep from "../../src/cep-promise.js"; -import CepPromiseError from "../../src/errors/cep-promise.js"; +import cep from '../../src/cep-promise.js'; +import CepPromiseError from '../../src/errors/cep-promise.js'; chai.use(chaiAsPromised); chai.use(chaiSubset); let expect = chai.expect; -describe("[unit] cep-promise for browser", () => { +describe('[unit] cep-promise for browser', () => { before(() => { // Mock browser behavior global.window = {}; nock.disableNetConnect(); }); - describe("when imported", () => { - it("should return a Function", () => { - expect(cep).to.be.a("function"); + describe('when imported', () => { + it('should return a Function', () => { + expect(cep).to.be.a('function'); }); }); - describe("when invoked", () => { - it("should return a Promise", () => { - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + describe('when invoked', () => { + it('should return a Promise', () => { + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') ); - const cepPromise = cep("05010000"); - expect(cepPromise.then).to.be.a("function"); - expect(cepPromise.catch).to.be.a("function"); + const cepPromise = cep('05010000'); + expect(cepPromise.then).to.be.a('function'); + expect(cepPromise.catch).to.be.a('function'); }); }); - describe("when invoked without arguments", () => { - it('should reject with "validation_error"', () => { + describe('when invoked without arguments', () => { + it('should reject with 'validation_error'', () => { return cep().catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { message: - "Você deve chamar o construtor utilizando uma String ou um Number.", - service: "cep_validation", + 'Você deve chamar o construtor utilizando uma String ou um Number.', + service: 'cep_validation', }, ], }); @@ -77,20 +77,20 @@ describe("[unit] cep-promise for browser", () => { }); }); - describe("when invoked with an Array", () => { - it('should reject with "validation_error"', () => { + describe('when invoked with an Array', () => { + it('should reject with 'validation_error'', () => { return cep([1, 2, 3]).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { message: - "Você deve chamar o construtor utilizando uma String ou um Number.", - service: "cep_validation", + 'Você deve chamar o construtor utilizando uma String ou um Number.', + service: 'cep_validation', }, ], }); @@ -98,20 +98,20 @@ describe("[unit] cep-promise for browser", () => { }); }); - describe("when invoked with an Object", () => { - it('should reject with "validation_error"', () => { + describe('when invoked with an Object', () => { + it('should reject with 'validation_error'', () => { return cep({ nintendo: true, ps: false, xbox: false }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { message: - "Você deve chamar o construtor utilizando uma String ou um Number.", - service: "cep_validation", + 'Você deve chamar o construtor utilizando uma String ou um Number.', + service: 'cep_validation', }, ], }); @@ -119,22 +119,22 @@ describe("[unit] cep-promise for browser", () => { }); }); - describe("when invoked with an Function", () => { - it('should reject with "validation_error"', () => { + describe('when invoked with an Function', () => { + it('should reject with 'validation_error'', () => { return cep(function zelda() { - return "link"; + return 'link'; }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { message: - "Você deve chamar o construtor utilizando uma String ou um Number.", - service: "cep_validation", + 'Você deve chamar o construtor utilizando uma String ou um Number.', + service: 'cep_validation', }, ], }); @@ -142,234 +142,234 @@ describe("[unit] cep-promise for browser", () => { }); }); - describe('when invoked with a valid "05010000" String', () => { - it("should fulfill with correct address", () => { - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + describe('when invoked with a valid '05010000' String', () => { + it('should fulfill with correct address', () => { + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') ); - return cep("05010000").then((address) => + return cep('05010000').then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', service: address.service, }) ); }); }); - describe("when invoked with a valid 5010000 Number", () => { - it("should fulfill with correct address", () => { - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + describe('when invoked with a valid 5010000 Number', () => { + it('should fulfill with correct address', () => { + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') ); return cep(5010000).then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', service: address.service, }) ); }); }); - describe("Should succeed only with viacep service", () => { - it("should fulfill with correct address", () => { - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + describe('Should succeed only with viacep service', () => { + it('should fulfill with correct address', () => { + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/99999999") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/99999999') .replyWithFile( 404, - path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') ); - return cep("05010000").then((address) => + return cep('05010000').then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "viacep", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'viacep', }) ); }); }); - describe("Should succeed only with widenet service", () => { - it("should fulfill with correct address", () => { - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + describe('Should succeed only with widenet service', () => { + it('should fulfill with correct address', () => { + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/99999999") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/99999999') .replyWithFile( 404, - path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') ); - return cep("5010000").then((address) => + return cep('5010000').then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "widenet", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'widenet', }) ); }); }); - describe("Should succeed only with brasilapi service", () => { - it("should fulfill with correct address", () => { - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + describe('Should succeed only with brasilapi service', () => { + it('should fulfill with correct address', () => { + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') ); - return cep("5010000").then((address) => + return cep('5010000').then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "brasilapi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'brasilapi', }) ); }); }); - describe('when invoked with an inexistent "99999999" CEP', () => { - it('should reject with "service_error"', () => { - nock("https://viacep.com.br") - .get("/ws/99999999/json/") + describe('when invoked with an inexistent '99999999' CEP', () => { + it('should reject with 'service_error'', () => { + nock('https://viacep.com.br') + .get('/ws/99999999/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/99999-999.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/99999-999.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/99999999") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/99999999') .replyWithFile( 404, - path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') ); - nock("https://api.postmon.com.br") - .get("/v1/cep/99999999") + nock('https://api.postmon.com.br') + .get('/v1/cep/99999999') .replyWithFile( 404, - path.join(__dirname, "/fixtures/postmon-cep-99999999-error.json") + path.join(__dirname, '/fixtures/postmon-cep-99999999-error.json') ); - return cep("99999999").catch((error) => { + return cep('99999999').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Todos os serviços de CEP retornaram erro.", - type: "service_error", + name: 'CepPromiseError', + message: 'Todos os serviços de CEP retornaram erro.', + type: 'service_error', errors: [ { - message: "CEP não encontrado na base do ViaCEP.", - service: "viacep", + message: 'CEP não encontrado na base do ViaCEP.', + service: 'viacep', }, { - message: "CEP não encontrado na base do WideNet.", - service: "widenet", + message: 'CEP não encontrado na base do WideNet.', + service: 'widenet', }, { - message: "CEP não encontrado na base do Postmon.", - service: "postmon", + message: 'CEP não encontrado na base do Postmon.', + service: 'postmon', }, ], }); @@ -377,19 +377,19 @@ describe("[unit] cep-promise for browser", () => { }); }); - describe('when invoked with an invalid "123456789" CEP', () => { - it('should reject with "validation_error"', () => { - return cep("123456789").catch((error) => { + describe('when invoked with an invalid '123456789' CEP', () => { + it('should reject with 'validation_error'', () => { + return cep('123456789').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "CEP deve conter exatamente 8 caracteres.", - type: "validation_error", + name: 'CepPromiseError', + message: 'CEP deve conter exatamente 8 caracteres.', + type: 'validation_error', errors: [ { - service: "cep_validation", - message: "CEP informado possui mais do que 8 caracteres.", + service: 'cep_validation', + message: 'CEP informado possui mais do que 8 caracteres.', }, ], }); @@ -397,47 +397,47 @@ describe("[unit] cep-promise for browser", () => { }); }); - describe("when http request fails both for all services with bad response", () => { - it('should reject with "service_error"', () => { - nock("https://viacep.com.br") - .get("/ws/05010000/json/") - .reply(400, "

Bad Request (400)

"); + describe('when http request fails both for all services with bad response', () => { + it('should reject with 'service_error'', () => { + nock('https://viacep.com.br') + .get('/ws/05010000/json/') + .reply(400, '

Bad Request (400)

'); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") - .reply(400, "

Bad Request (400)

"); + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') + .reply(400, '

Bad Request (400)

'); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") - .reply(400, "

Bad Request (400)

"); - nock("https://api.postmon.com.br") - .get("/v1/cep/05010000") - .reply(400, "

Bad Request (400)

"); + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') + .reply(400, '

Bad Request (400)

'); + nock('https://api.postmon.com.br') + .get('/v1/cep/05010000') + .reply(400, '

Bad Request (400)

'); - return cep("05010000").catch((error) => { + return cep('05010000').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Todos os serviços de CEP retornaram erro.", - type: "service_error", + name: 'CepPromiseError', + message: 'Todos os serviços de CEP retornaram erro.', + type: 'service_error', errors: [ { - message: "Erro ao se conectar com o serviço ViaCEP.", - service: "viacep", + message: 'Erro ao se conectar com o serviço ViaCEP.', + service: 'viacep', }, { - message: "Erro ao se conectar com o serviço WideNet.", - service: "widenet", + message: 'Erro ao se conectar com o serviço WideNet.', + service: 'widenet', }, { - message: "Erro ao se conectar com o serviço Postmon.", - service: "postmon", + message: 'Erro ao se conectar com o serviço Postmon.', + service: 'postmon', }, { - name: "ServiceError", - message: "CEP não encontrado na base do BrasilAPI.", - service: "brasilapi", + name: 'ServiceError', + message: 'CEP não encontrado na base do BrasilAPI.', + service: 'brasilapi', }, ], }); diff --git a/test/unit/cep-promise-node.spec.js b/test/unit/cep-promise-node.spec.js index 2e3a5a00..761e1c66 100644 --- a/test/unit/cep-promise-node.spec.js +++ b/test/unit/cep-promise-node.spec.js @@ -1,93 +1,93 @@ -"use strict"; +'use strict'; -import chai from "chai"; -import chaiAsPromised from "chai-as-promised"; -import chaiSubset from "chai-subset"; -import nock from "nock"; -import path from "path"; +import chai from 'chai'; +import chaiAsPromised from 'chai-as-promised'; +import chaiSubset from 'chai-subset'; +import nock from 'nock'; +import path from 'path'; -import cep from "../../src/cep-promise.js"; -import CepPromiseError from "../../src/errors/cep-promise.js"; +import cep from '../../src/cep-promise.js'; +import CepPromiseError from '../../src/errors/cep-promise.js'; chai.use(chaiAsPromised); chai.use(chaiSubset); let expect = chai.expect; -describe("[unit] cep-promise for node", () => { +describe('[unit] cep-promise for node', () => { before(() => { nock.disableNetConnect(); }); - describe("when imported", () => { - it("should return a Function", () => { - expect(cep).to.be.a("function"); + describe('when imported', () => { + it('should return a Function', () => { + expect(cep).to.be.a('function'); }); }); - describe("when invoked", () => { - it("should return a Promise", () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('when invoked', () => { + it('should return a Promise', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') ); - nock("https://api.postmon.com.br") - .get("/v1/cep/05010000") + nock('https://api.postmon.com.br') + .get('/v1/cep/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') ); - const cepPromise = cep("05010000"); - expect(cepPromise.then).to.be.a("function"); - expect(cepPromise.catch).to.be.a("function"); + const cepPromise = cep('05010000'); + expect(cepPromise.then).to.be.a('function'); + expect(cepPromise.catch).to.be.a('function'); }); }); - describe("when invoked without arguments", () => { - it('should reject with "validation_error"', () => { + describe('when invoked without arguments', () => { + it('should reject with 'validation_error'', () => { return cep().catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { message: - "Você deve chamar o construtor utilizando uma String ou um Number.", - service: "cep_validation", + 'Você deve chamar o construtor utilizando uma String ou um Number.', + service: 'cep_validation', }, ], }); @@ -95,20 +95,20 @@ describe("[unit] cep-promise for node", () => { }); }); - describe("when invoked with an Array", () => { - it('should reject with "validation_error"', () => { + describe('when invoked with an Array', () => { + it('should reject with 'validation_error'', () => { return cep([1, 2, 3]).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { message: - "Você deve chamar o construtor utilizando uma String ou um Number.", - service: "cep_validation", + 'Você deve chamar o construtor utilizando uma String ou um Number.', + service: 'cep_validation', }, ], }); @@ -116,20 +116,20 @@ describe("[unit] cep-promise for node", () => { }); }); - describe("when invoked with an Object", () => { - it('should reject with "validation_error"', () => { + describe('when invoked with an Object', () => { + it('should reject with 'validation_error'', () => { return cep({ nintendo: true, ps: false, xbox: false }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { message: - "Você deve chamar o construtor utilizando uma String ou um Number.", - service: "cep_validation", + 'Você deve chamar o construtor utilizando uma String ou um Number.', + service: 'cep_validation', }, ], }); @@ -137,22 +137,22 @@ describe("[unit] cep-promise for node", () => { }); }); - describe("when invoked with an Function", () => { - it('should reject with "validation_error"', () => { + describe('when invoked with an Function', () => { + it('should reject with 'validation_error'', () => { return cep(function zelda() { - return "link"; + return 'link'; }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { message: - "Você deve chamar o construtor utilizando uma String ou um Number.", - service: "cep_validation", + 'Você deve chamar o construtor utilizando uma String ou um Number.', + service: 'cep_validation', }, ], }); @@ -160,534 +160,534 @@ describe("[unit] cep-promise for node", () => { }); }); - describe('when invoked with a valid "05010000" String', () => { - it("should fulfill with correct address", () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('when invoked with a valid '05010000' String', () => { + it('should fulfill with correct address', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') ); - return cep("05010000").then((address) => + return cep('05010000').then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', service: address.service, }) ); }); }); - describe("when invoked with a valid 5010000 Number", () => { - it("should fulfill with correct address", () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('when invoked with a valid 5010000 Number', () => { + it('should fulfill with correct address', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') ); return cep(5010000).then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', service: address.service, }) ); }); }); - describe("Should succeed only with correios service", () => { - it("should fulfill with correct address", () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('Should succeed only with correios service', () => { + it('should fulfill with correct address', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-99999999-error.json") + path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') ); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') ); - nock("https://cep.widenet.host") - .get("/file/apicep/05010-000.json") + nock('https://cep.widenet.host') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/99999999") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/99999999') .replyWithFile( 404, - path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') ); - return cep("05010000").then((address) => + return cep('05010000').then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "correios", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'correios', }) ); }); }); - describe("Should succeed only with correios-alt service", () => { - it("should fulfill with correct address", () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('Should succeed only with correios-alt service', () => { + it('should fulfill with correct address', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 500, - path.join(__dirname, "/fixtures/response-unknown-format.xml") + path.join(__dirname, '/fixtures/response-unknown-format.xml') ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 404, - path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') ); - nock("https://api.postmon.com.br") - .get("/v1/cep/05010000") + nock('https://api.postmon.com.br') + .get('/v1/cep/05010000') .replyWithFile( 404, - path.join(__dirname, "/fixtures/postmon-cep-99999999-error.json") + path.join(__dirname, '/fixtures/postmon-cep-99999999-error.json') ); - return cep("05010000").then((address) => { + return cep('05010000').then((address) => { expect(address) .to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "correios-alt", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'correios-alt', }); }); }); }); - describe("Should succeed only with viacep service", () => { - it("should fulfill with correct address", () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('Should succeed only with viacep service', () => { + it('should fulfill with correct address', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 500, - path.join(__dirname, "/fixtures/response-unknown-format.xml") + path.join(__dirname, '/fixtures/response-unknown-format.xml') ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-99999999-error.json") + path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') ); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/99999999") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/99999999') .replyWithFile( 404, - path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') ); - return cep("05010000").then((address) => + return cep('05010000').then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "viacep", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'viacep', }) ); }); }); - describe("Should succeed only with widenet service", () => { - it("should fulfill with correct address", () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('Should succeed only with widenet service', () => { + it('should fulfill with correct address', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 500, - path.join(__dirname, "/fixtures/response-unknown-format.xml") + path.join(__dirname, '/fixtures/response-unknown-format.xml') ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-99999999-error.json") + path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') ); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/99999999") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/99999999') .replyWithFile( 404, - path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') ); - return cep("5010000").then((address) => + return cep('5010000').then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "widenet", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'widenet', }) ); }); }); - describe("Should succeed only with brasilapi service", () => { - it("should fulfill with correct address", () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('Should succeed only with brasilapi service', () => { + it('should fulfill with correct address', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 500, - path.join(__dirname, "/fixtures/response-unknown-format.xml") + path.join(__dirname, '/fixtures/response-unknown-format.xml') ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-99999999-error.json") + path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') ); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') ); - return cep("5010000").then((address) => + return cep('5010000').then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "brasilapi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'brasilapi', }) ); }); }); - describe("when its not possible to parse the returned XML and then succeed to one failover service", () => { - it("should fulfill with correct address", () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('when its not possible to parse the returned XML and then succeed to one failover service', () => { + it('should fulfill with correct address', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-bad-xml.xml") + path.join(__dirname, '/fixtures/response-bad-xml.xml') ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') ); - return cep("5010000").then((address) => + return cep('5010000').then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', service: address.service, }) ); }); }); - describe("when http request to Correios fails and then succeed to the failover service", () => { - it("should fulfill with correct address", () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('when http request to Correios fails and then succeed to the failover service', () => { + it('should fulfill with correct address', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithError( - "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') ); - return cep("5010000").then((address) => + return cep('5010000').then((address) => expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', service: address.service, }) ); }); }); - describe('when invoked with an inexistent "99999999" CEP', () => { - it('should reject with "service_error"', () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('when invoked with an inexistent '99999999' CEP', () => { + it('should reject with 'service_error'', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 500, - path.join(__dirname, "/fixtures/response-cep-not-found.xml") + path.join(__dirname, '/fixtures/response-cep-not-found.xml') ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-99999999-error.json") + path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') ); - nock("https://viacep.com.br") - .get("/ws/99999999/json/") + nock('https://viacep.com.br') + .get('/ws/99999999/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-99999999-error.json") + path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') ); - nock("https://api.postmon.com.br") - .get("/v1/cep/99999999") + nock('https://api.postmon.com.br') + .get('/v1/cep/99999999') .replyWithFile( 404, - path.join(__dirname, "/fixtures/postmon-cep-99999999-error.json") + path.join(__dirname, '/fixtures/postmon-cep-99999999-error.json') ); - nock("https://cdn.apicep.com") - .get("/file/apicep/99999-999.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/99999-999.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-99999999-error.json") + path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/99999999") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/99999999') .replyWithFile( 404, - path.join(__dirname, "/fixtures/brasilapi-cep-99999999-error.json") + path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') ); - return cep("99999999").catch((error) => { + return cep('99999999').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Todos os serviços de CEP retornaram erro.", - type: "service_error", + name: 'CepPromiseError', + message: 'Todos os serviços de CEP retornaram erro.', + type: 'service_error', errors: [ { - message: "CEP NAO ENCONTRADO", - service: "correios", + message: 'CEP NAO ENCONTRADO', + service: 'correios', }, { - message: "CEP não encontrado na base dos Correios.", - service: "correios-alt", + message: 'CEP não encontrado na base dos Correios.', + service: 'correios-alt', }, { - message: "CEP não encontrado na base do ViaCEP.", - service: "viacep", + message: 'CEP não encontrado na base do ViaCEP.', + service: 'viacep', }, { - message: "CEP não encontrado na base do WideNet.", - service: "widenet", + message: 'CEP não encontrado na base do WideNet.', + service: 'widenet', }, { - message: "CEP não encontrado na base do Postmon.", - service: "postmon", + message: 'CEP não encontrado na base do Postmon.', + service: 'postmon', }, ], }); @@ -695,19 +695,19 @@ describe("[unit] cep-promise for node", () => { }); }); - describe('when invoked with an invalid "123456789" CEP', () => { - it('should reject with "validation_error"', () => { - return cep("123456789").catch((error) => { + describe('when invoked with an invalid '123456789' CEP', () => { + it('should reject with 'validation_error'', () => { + return cep('123456789').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "CEP deve conter exatamente 8 caracteres.", - type: "validation_error", + name: 'CepPromiseError', + message: 'CEP deve conter exatamente 8 caracteres.', + type: 'validation_error', errors: [ { - service: "cep_validation", - message: "CEP informado possui mais do que 8 caracteres.", + service: 'cep_validation', + message: 'CEP informado possui mais do que 8 caracteres.', }, ], }); @@ -715,58 +715,58 @@ describe("[unit] cep-promise for node", () => { }); }); - describe("when http request fails both for primary and secondary service with bad response", () => { - it('should reject with "service_error"', () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('when http request fails both for primary and secondary service with bad response', () => { + it('should reject with 'service_error'', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithError( - "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") - .reply(400, "

Bad Request (400)

"); + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') + .reply(400, '

Bad Request (400)

'); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") - .reply(400, "

Bad Request (400)

"); + nock('https://viacep.com.br') + .get('/ws/05010000/json/') + .reply(400, '

Bad Request (400)

'); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") - .reply(400, "

Bad Request (400)

"); + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') + .reply(400, '

Bad Request (400)

'); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") - .reply(400, "

Bad Request (400)

"); + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') + .reply(400, '

Bad Request (400)

'); - return cep("05010000").catch((error) => { + return cep('05010000').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Todos os serviços de CEP retornaram erro.", - type: "service_error", + name: 'CepPromiseError', + message: 'Todos os serviços de CEP retornaram erro.', + type: 'service_error', errors: [ { - message: "Erro ao se conectar com o serviço dos Correios.", - service: "correios", + message: 'Erro ao se conectar com o serviço dos Correios.', + service: 'correios', }, { - message: "Erro ao se conectar com o serviço dos Correios Alt.", - service: "correios-alt", + message: 'Erro ao se conectar com o serviço dos Correios Alt.', + service: 'correios-alt', }, { - message: "Erro ao se conectar com o serviço ViaCEP.", - service: "viacep", + message: 'Erro ao se conectar com o serviço ViaCEP.', + service: 'viacep', }, { - message: "Erro ao se conectar com o serviço WideNet.", - service: "widenet", + message: 'Erro ao se conectar com o serviço WideNet.', + service: 'widenet', }, { - name: "ServiceError", - message: "CEP não encontrado na base do BrasilAPI.", - service: "brasilapi", + name: 'ServiceError', + message: 'CEP não encontrado na base do BrasilAPI.', + service: 'brasilapi', }, ], }); @@ -774,59 +774,59 @@ describe("[unit] cep-promise for node", () => { }); }); - describe("when http request has unformatted xml and alternatives services fails", () => { - it('should reject with "service_error"', () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('when http request has unformatted xml and alternatives services fails', () => { + it('should reject with 'service_error'', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-bad-xml.xml") + path.join(__dirname, '/fixtures/response-bad-xml.xml') ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .reply(200, { erro: true }); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") - .reply(400, "

Bad Request (400)

"); + nock('https://viacep.com.br') + .get('/ws/05010000/json/') + .reply(400, '

Bad Request (400)

'); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") - .reply(400, "

Bad Request (400)

"); + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') + .reply(400, '

Bad Request (400)

'); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") - .reply(400, "

Bad Request (400)

"); + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') + .reply(400, '

Bad Request (400)

'); - return cep("05010000").catch((error) => { + return cep('05010000').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Todos os serviços de CEP retornaram erro.", - type: "service_error", + name: 'CepPromiseError', + message: 'Todos os serviços de CEP retornaram erro.', + type: 'service_error', errors: [ { - message: "Não foi possível interpretar o XML de resposta.", - service: "correios", + message: 'Não foi possível interpretar o XML de resposta.', + service: 'correios', }, { - message: "CEP não encontrado na base dos Correios.", - service: "correios-alt", + message: 'CEP não encontrado na base dos Correios.', + service: 'correios-alt', }, { - message: "Erro ao se conectar com o serviço ViaCEP.", - service: "viacep", + message: 'Erro ao se conectar com o serviço ViaCEP.', + service: 'viacep', }, { - message: "Erro ao se conectar com o serviço WideNet.", - service: "widenet", + message: 'Erro ao se conectar com o serviço WideNet.', + service: 'widenet', }, { - name: "ServiceError", - message: "CEP não encontrado na base do BrasilAPI.", - service: "brasilapi", + name: 'ServiceError', + message: 'CEP não encontrado na base do BrasilAPI.', + service: 'brasilapi', }, ], }); @@ -834,63 +834,63 @@ describe("[unit] cep-promise for node", () => { }); }); - describe("when http request fails both for primary and secondary service with error", () => { - it('should reject with "service_error"', () => { - nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('when http request fails both for primary and secondary service with error', () => { + it('should reject with 'service_error'', () => { + nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithError( - "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' ); - nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .reply(200, { erro: true }); - nock("https://viacep.com.br") - .get("/ws/05010000/json/") + nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithError( - "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' ); - nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithError( - "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' ); - nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithError( - "getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443" + 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' ); - return cep("05010000").catch((error) => { + return cep('05010000').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Todos os serviços de CEP retornaram erro.", - type: "service_error", + name: 'CepPromiseError', + message: 'Todos os serviços de CEP retornaram erro.', + type: 'service_error', errors: [ { - message: "Erro ao se conectar com o serviço dos Correios.", - service: "correios", + message: 'Erro ao se conectar com o serviço dos Correios.', + service: 'correios', }, { - message: "CEP não encontrado na base dos Correios.", - service: "correios-alt", + message: 'CEP não encontrado na base dos Correios.', + service: 'correios-alt', }, { - message: "Erro ao se conectar com o serviço ViaCEP.", - service: "viacep", + message: 'Erro ao se conectar com o serviço ViaCEP.', + service: 'viacep', }, { - message: "Erro ao se conectar com o serviço WideNet.", - service: "widenet", + message: 'Erro ao se conectar com o serviço WideNet.', + service: 'widenet', }, { - message: "Erro ao se conectar com o serviço BrasilAPI.", - service: "brasilapi", + message: 'Erro ao se conectar com o serviço BrasilAPI.', + service: 'brasilapi', }, ], }); diff --git a/test/unit/cep-promise-providers.spec.js b/test/unit/cep-promise-providers.spec.js index ece7fc57..a5d2ddaa 100644 --- a/test/unit/cep-promise-providers.spec.js +++ b/test/unit/cep-promise-providers.spec.js @@ -1,36 +1,36 @@ -"use strict"; +'use strict'; -import chai from "chai"; -import chaiSubset from "chai-subset"; -import nock from "nock"; -import path from "path"; +import chai from 'chai'; +import chaiSubset from 'chai-subset'; +import nock from 'nock'; +import path from 'path'; -import cep from "../../src/cep-promise.js"; -import CepPromiseError from "../../src/errors/cep-promise.js"; -import { getAvailableServices } from "../../src/services/index.js"; +import cep from '../../src/cep-promise.js'; +import CepPromiseError from '../../src/errors/cep-promise.js'; +import { getAvailableServices } from '../../src/services/index.js'; chai.use(chaiSubset); let expect = chai.expect; -describe("when invoked with providers parameter", () => { +describe('when invoked with providers parameter', () => { before(() => { nock.disableNetConnect(); }); - describe("and the providers param is a string", () => { - it('should reject with "validation_error"', () => { - return cep("05010000", { providers: "viacep" }).catch((error) => { + describe('and the providers param is a string', () => { + it('should reject with 'validation_error'', () => { + return cep('05010000', { providers: 'viacep' }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { - service: "providers_validation", - message: "O parâmetro providers deve ser uma lista.", + service: 'providers_validation', + message: 'O parâmetro providers deve ser uma lista.', }, ], }); @@ -38,19 +38,19 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is a integer", () => { - it('should reject with "validation_error"', () => { - return cep("05010000", { providers: 123 }).catch((error) => { + describe('and the providers param is a integer', () => { + it('should reject with 'validation_error'', () => { + return cep('05010000', { providers: 123 }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { - service: "providers_validation", - message: "O parâmetro providers deve ser uma lista.", + service: 'providers_validation', + message: 'O parâmetro providers deve ser uma lista.', }, ], }); @@ -58,19 +58,19 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is a object", () => { - it('should reject with "validation_error"', () => { - return cep("05010000", { providers: {} }).catch((error) => { + describe('and the providers param is a object', () => { + it('should reject with 'validation_error'', () => { + return cep('05010000', { providers: {} }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { - service: "providers_validation", - message: "O parâmetro providers deve ser uma lista.", + service: 'providers_validation', + message: 'O parâmetro providers deve ser uma lista.', }, ], }); @@ -78,19 +78,19 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is a function", () => { - it('should reject with "validation_error"', () => { - return cep("05010000", { providers: () => () => {} }).catch((error) => { + describe('and the providers param is a function', () => { + it('should reject with 'validation_error'', () => { + return cep('05010000', { providers: () => () => {} }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - name: "CepPromiseError", - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + name: 'CepPromiseError', + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { - service: "providers_validation", - message: "O parâmetro providers deve ser uma lista.", + service: 'providers_validation', + message: 'O parâmetro providers deve ser uma lista.', }, ], }); @@ -98,22 +98,22 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is a invalid array", () => { - it('should reject with "validation_error"', () => { + describe('and the providers param is a invalid array', () => { + it('should reject with 'validation_error'', () => { const availableProviders = Object.keys(getAvailableServices()); - return cep("05010000", { providers: [123, "viacep"] }).catch((error) => { + return cep('05010000', { providers: [123, 'viacep'] }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) .and.containSubset({ - message: "Erro ao inicializar a instância do CepPromise.", - type: "validation_error", + message: 'Erro ao inicializar a instância do CepPromise.', + type: 'validation_error', errors: [ { - message: `O provider "123" é inválido. Os providers disponíveis são: ["${availableProviders.join( - '", "' - )}"].`, - service: "providers_validation", + message: `O provider '123' é inválido. Os providers disponíveis são: ['${availableProviders.join( + '', '' + )}'].`, + service: 'providers_validation', }, ], }); @@ -121,50 +121,50 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is ['viacep']", () => { - it("should call only viacep service", () => { - const correiosMock = nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('and the providers param is ['viacep']', () => { + it('should call only viacep service', () => { + const correiosMock = nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - const correiosAltMock = nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + const correiosAltMock = nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - const viaCepMock = nock("https://viacep.com.br") - .get("/ws/05010000/json/") + const viaCepMock = nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - const postmonMock = nock("https://api.postmon.com.br") - .get("/v1/cep/05010000") + const postmonMock = nock('https://api.postmon.com.br') + .get('/v1/cep/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') ); - const wideNetMock = nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + const wideNetMock = nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - return cep("05010000", { providers: ["viacep"] }).then((address) => { + return cep('05010000', { providers: ['viacep'] }).then((address) => { expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "viacep", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'viacep', }); expect(viaCepMock.isDone()).to.be.equal(true); @@ -176,50 +176,50 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is ['postmon']", () => { - it("should call only postmon service", () => { - const correiosMock = nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('and the providers param is ['postmon']', () => { + it('should call only postmon service', () => { + const correiosMock = nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - const correiosAltMock = nock("https://buscacepinter.correios.com.br") - .post("/app/cep/carrega-cep.php") + const correiosAltMock = nock('https://buscacepinter.correios.com.br') + .post('/app/cep/carrega-cep.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - const viaCepMock = nock("https://viacep.com.br") - .get("/ws/05010000/json/") + const viaCepMock = nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - const postmonMock = nock("https://api.postmon.com.br") - .get("/v1/cep/05010000") + const postmonMock = nock('https://api.postmon.com.br') + .get('/v1/cep/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') ); - const wideNetMock = nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + const wideNetMock = nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - return cep("05010000", { providers: ["postmon"] }).then((address) => { + return cep('05010000', { providers: ['postmon'] }).then((address) => { expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "postmon", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'postmon', }); expect(viaCepMock.isDone()).to.be.equal(false); @@ -231,50 +231,50 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is ['widenet']", () => { - it("should call only widenet service", () => { - const correiosMock = nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('and the providers param is ['widenet']', () => { + it('should call only widenet service', () => { + const correiosMock = nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - const correiosAltMock = nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + const correiosAltMock = nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - const viaCepMock = nock("https://viacep.com.br") - .get("/ws/05010000/json/") + const viaCepMock = nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - const wideNetMock = nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + const wideNetMock = nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - const postmonMock = nock("https://api.postmon.com.br") - .get("/v1/cep/05010000") + const postmonMock = nock('https://api.postmon.com.br') + .get('/v1/cep/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') ); - return cep("05010000", { providers: ["widenet"] }).then((address) => { + return cep('05010000', { providers: ['widenet'] }).then((address) => { expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "widenet", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'widenet', }); expect(wideNetMock.isDone()).to.be.equal(true); @@ -286,50 +286,50 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is ['correios']", () => { - it("should call only correios service", () => { - const correiosMock = nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('and the providers param is ['correios']', () => { + it('should call only correios service', () => { + const correiosMock = nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - const postmonMock = nock("https://api.postmon.com.br") - .get("/v1/cep/05010000") + const postmonMock = nock('https://api.postmon.com.br') + .get('/v1/cep/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') ); - const correiosAltMock = nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + const correiosAltMock = nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - const viaCepMock = nock("https://viacep.com.br") - .get("/ws/05010000/json/") + const viaCepMock = nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - const wideNetMock = nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + const wideNetMock = nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - return cep("05010000", { providers: ["correios"] }).then((address) => { + return cep('05010000', { providers: ['correios'] }).then((address) => { expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "correios", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'correios', }); expect(correiosMock.isDone()).to.be.equal(true); @@ -341,51 +341,51 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is ['correios-alt']", () => { - it("should call only correios alt service", () => { - const correiosMock = nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('and the providers param is ['correios-alt']', () => { + it('should call only correios alt service', () => { + const correiosMock = nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - const postmonMock = nock("https://api.postmon.com.br") - .get("/v1/cep/05010000") + const postmonMock = nock('https://api.postmon.com.br') + .get('/v1/cep/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') ); - const correiosAltMock = nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + const correiosAltMock = nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - const viaCepMock = nock("https://viacep.com.br") - .get("/ws/05010000/json/") + const viaCepMock = nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - const wideNetMock = nock("https://cep.widenet.host") - .get("/file/apicep/05010-000.json") + const wideNetMock = nock('https://cep.widenet.host') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - return cep("05010000", { providers: ["correios-alt"] }).then( + return cep('05010000', { providers: ['correios-alt'] }).then( (address) => { expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "correios-alt", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'correios-alt', }); expect(correiosMock.isDone()).to.be.equal(false); @@ -398,58 +398,58 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is ['brasilapi']", () => { - it("should call only brasilapi service", () => { - const correiosMock = nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('and the providers param is ['brasilapi']', () => { + it('should call only brasilapi service', () => { + const correiosMock = nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - const correiosAltMock = nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + const correiosAltMock = nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - const postmonMock = nock("https://api.postmon.com.br") - .get("/v1/cep/05010000") + const postmonMock = nock('https://api.postmon.com.br') + .get('/v1/cep/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') ); - const viaCepMock = nock("https://viacep.com.br") - .get("/ws/05010000/json/") + const viaCepMock = nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - const wideNetMock = nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + const wideNetMock = nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - const brasilAPIMock = nock("https://brasilapi.com.br/") - .get("/api/cep/v1/05010000") + const brasilAPIMock = nock('https://brasilapi.com.br/') + .get('/api/cep/v1/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/brasilapi-cep-05010000-found.json") + path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') ); - return cep("05010000", { providers: ["brasilapi"] }).then((address) => { + return cep('05010000', { providers: ['brasilapi'] }).then((address) => { expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", - service: "brasilapi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: 'brasilapi', }); expect(correiosMock.isDone()).to.be.equal(false); @@ -462,51 +462,51 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is ['correios, viacep']", () => { - it("should call only correios and viacep services", () => { - const correiosMock = nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('and the providers param is ['correios, viacep']', () => { + it('should call only correios and viacep services', () => { + const correiosMock = nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - const correiosAltMock = nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + const correiosAltMock = nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - const viaCepMock = nock("https://viacep.com.br") - .get("/ws/05010000/json/") + const viaCepMock = nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - const wideNetMock = nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + const wideNetMock = nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - const postmonMock = nock("https://api.postmon.com.br") - .get("/v1/cep/05010000") + const postmonMock = nock('https://api.postmon.com.br') + .get('/v1/cep/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') ); - return cep("05010000", { providers: ["correios", "viacep"] }).then( + return cep('05010000', { providers: ['correios', 'viacep'] }).then( (address) => { expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', service: address.service, }); @@ -520,50 +520,50 @@ describe("when invoked with providers parameter", () => { }); }); - describe("and the providers param is []", () => { - it("should call all services", () => { - const correiosMock = nock("https://apps.correios.com.br") - .post("/SigepMasterJPA/AtendeClienteService/AtendeCliente") + describe('and the providers param is []', () => { + it('should call all services', () => { + const correiosMock = nock('https://apps.correios.com.br') + .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( 200, - path.join(__dirname, "/fixtures/response-cep-05010000-found.xml") + path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') ); - const correiosAltMock = nock("https://buscacepinter.correios.com.br") - .post("/app/endereco/carrega-cep-endereco.php") + const correiosAltMock = nock('https://buscacepinter.correios.com.br') + .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, - path.join(__dirname, "/fixtures/correios-alt-cep-05010000-found.json") + path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') ); - const postmonMock = nock("https://api.postmon.com.br") - .get("/v1/cep/05010000") + const postmonMock = nock('https://api.postmon.com.br') + .get('/v1/cep/05010000') .replyWithFile( 200, - path.join(__dirname, "/fixtures/postmon-cep-05010000-found.json") + path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') ); - const viaCepMock = nock("https://viacep.com.br") - .get("/ws/05010000/json/") + const viaCepMock = nock('https://viacep.com.br') + .get('/ws/05010000/json/') .replyWithFile( 200, - path.join(__dirname, "/fixtures/viacep-cep-05010000-found.json") + path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') ); - const wideNetMock = nock("https://cdn.apicep.com") - .get("/file/apicep/05010-000.json") + const wideNetMock = nock('https://cdn.apicep.com') + .get('/file/apicep/05010-000.json') .replyWithFile( 200, - path.join(__dirname, "/fixtures/widenet-cep-05010000-found.json") + path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') ); - return cep("05010000", { providers: [] }).then((address) => { + return cep('05010000', { providers: [] }).then((address) => { expect(address).to.deep.equal({ - cep: "05010000", - state: "SP", - city: "São Paulo", - neighborhood: "Perdizes", - street: "Rua Caiubi", + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', service: address.service, }); diff --git a/test/unit/cep-promise-timeout.spec.js b/test/unit/cep-promise-timeout.spec.js index 910af40a..b76f9aa6 100644 --- a/test/unit/cep-promise-timeout.spec.js +++ b/test/unit/cep-promise-timeout.spec.js @@ -18,7 +18,7 @@ describe('when invoked with timeout parameter', () => { }) describe('and the providers exceed the timeout', () => { - it('should reject with "service_error"', () => { + it('should reject with 'service_error'', () => { nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .delay(3) From 3ce91b77c15305ce97c5bd13891aed659995cabc Mon Sep 17 00:00:00 2001 From: Rodrigo Teixeira Andreotti Date: Thu, 28 Mar 2024 19:03:25 -0300 Subject: [PATCH 08/10] Rollbak comas --- test/e2e/cep-promise.spec.js | 56 ++-- test/unit/cep-promise-browser.spec.js | 194 +++++++------- test/unit/cep-promise-node.spec.js | 324 ++++++++++++------------ test/unit/cep-promise-providers.spec.js | 302 +++++++++++----------- 4 files changed, 438 insertions(+), 438 deletions(-) diff --git a/test/e2e/cep-promise.spec.js b/test/e2e/cep-promise.spec.js index 6b416601..292c6134 100644 --- a/test/e2e/cep-promise.spec.js +++ b/test/e2e/cep-promise.spec.js @@ -1,22 +1,22 @@ -'use strict'; +'use strict' -import chai from 'chai'; -import chaiAsPromised from 'chai-as-promised'; -import chaiSubset from 'chai-subset'; -import nock from 'nock'; +import chai from 'chai' +import chaiAsPromised from 'chai-as-promised' +import chaiSubset from 'chai-subset' +import nock from 'nock' -import cep from '../../src/cep-promise.js'; -import CepPromiseError from '../../src/errors/cep-promise.js'; +import cep from '../../src/cep-promise.js' +import CepPromiseError from '../../src/errors/cep-promise.js' -chai.use(chaiAsPromised); -chai.use(chaiSubset); +chai.use(chaiAsPromised) +chai.use(chaiSubset) -let expect = chai.expect; +let expect = chai.expect describe('[e2e] cep-promise', () => { before(() => { - nock.enableNetConnect(); - }); + nock.enableNetConnect() + }) describe('when invoked with a valid '05010000' string', () => { it('should fulfill with correct address', () => @@ -28,13 +28,13 @@ describe('[e2e] cep-promise', () => { neighborhood: 'Perdizes', street: 'Rua Caiubi', service: address.service, - }); - })); - }); + }) + })) + }) describe('when invoked with a valid 05010000 number', () => { it('should fulfill with correct address', async () => { - const address = await cep(5010000); + const address = await cep(5010000) expect(address).to.deep.equal({ cep: '05010000', @@ -43,9 +43,9 @@ describe('[e2e] cep-promise', () => { neighborhood: 'Perdizes', street: 'Rua Caiubi', service: address.service, - }); - }); - }); + }) + }) + }) describe('when invoked with an inexistent '99999999' CEP', () => { it('should reject with 'service_error'', () => { @@ -82,10 +82,10 @@ describe('[e2e] cep-promise', () => { service: 'brasilapi', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when invoked with an invalid '123456789' CEP', () => { it('should reject with 'validation_error'', () => { @@ -102,8 +102,8 @@ describe('[e2e] cep-promise', () => { message: 'CEP informado possui mais do que 8 caracteres.', }, ], - }); - }); - }); - }); -}); + }) + }) + }) + }) +}) diff --git a/test/unit/cep-promise-browser.spec.js b/test/unit/cep-promise-browser.spec.js index 4f818d0b..7eadcd3e 100644 --- a/test/unit/cep-promise-browser.spec.js +++ b/test/unit/cep-promise-browser.spec.js @@ -1,31 +1,31 @@ -'use strict'; +'use strict' -import chai from 'chai'; -import chaiAsPromised from 'chai-as-promised'; -import chaiSubset from 'chai-subset'; -import nock from 'nock'; -import path from 'path'; +import chai from 'chai' +import chaiAsPromised from 'chai-as-promised' +import chaiSubset from 'chai-subset' +import nock from 'nock' +import path from 'path' -import cep from '../../src/cep-promise.js'; -import CepPromiseError from '../../src/errors/cep-promise.js'; +import cep from '../../src/cep-promise.js' +import CepPromiseError from '../../src/errors/cep-promise.js' -chai.use(chaiAsPromised); -chai.use(chaiSubset); +chai.use(chaiAsPromised) +chai.use(chaiSubset) -let expect = chai.expect; +let expect = chai.expect describe('[unit] cep-promise for browser', () => { before(() => { // Mock browser behavior - global.window = {}; - nock.disableNetConnect(); - }); + global.window = {} + nock.disableNetConnect() + }) describe('when imported', () => { it('should return a Function', () => { - expect(cep).to.be.a('function'); - }); - }); + expect(cep).to.be.a('function') + }) + }) describe('when invoked', () => { it('should return a Promise', () => { @@ -34,27 +34,27 @@ describe('[unit] cep-promise for browser', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ); + ) - const cepPromise = cep('05010000'); - expect(cepPromise.then).to.be.a('function'); - expect(cepPromise.catch).to.be.a('function'); - }); - }); + const cepPromise = cep('05010000') + expect(cepPromise.then).to.be.a('function') + expect(cepPromise.catch).to.be.a('function') + }) + }) describe('when invoked without arguments', () => { it('should reject with 'validation_error'', () => { @@ -72,10 +72,10 @@ describe('[unit] cep-promise for browser', () => { service: 'cep_validation', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when invoked with an Array', () => { it('should reject with 'validation_error'', () => { @@ -93,10 +93,10 @@ describe('[unit] cep-promise for browser', () => { service: 'cep_validation', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when invoked with an Object', () => { it('should reject with 'validation_error'', () => { @@ -114,15 +114,15 @@ describe('[unit] cep-promise for browser', () => { service: 'cep_validation', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when invoked with an Function', () => { it('should reject with 'validation_error'', () => { return cep(function zelda() { - return 'link'; + return 'link' }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -137,10 +137,10 @@ describe('[unit] cep-promise for browser', () => { service: 'cep_validation', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when invoked with a valid '05010000' String', () => { it('should fulfill with correct address', () => { @@ -149,21 +149,21 @@ describe('[unit] cep-promise for browser', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ); + ) return cep('05010000').then((address) => expect(address).to.deep.equal({ @@ -174,9 +174,9 @@ describe('[unit] cep-promise for browser', () => { street: 'Rua Caiubi', service: address.service, }) - ); - }); - }); + ) + }) + }) describe('when invoked with a valid 5010000 Number', () => { it('should fulfill with correct address', () => { @@ -185,21 +185,21 @@ describe('[unit] cep-promise for browser', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ); + ) return cep(5010000).then((address) => expect(address).to.deep.equal({ @@ -210,9 +210,9 @@ describe('[unit] cep-promise for browser', () => { street: 'Rua Caiubi', service: address.service, }) - ); - }); - }); + ) + }) + }) describe('Should succeed only with viacep service', () => { it('should fulfill with correct address', () => { @@ -221,21 +221,21 @@ describe('[unit] cep-promise for browser', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/99999999') .replyWithFile( 404, path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ); + ) return cep('05010000').then((address) => expect(address).to.deep.equal({ @@ -246,9 +246,9 @@ describe('[unit] cep-promise for browser', () => { street: 'Rua Caiubi', service: 'viacep', }) - ); - }); - }); + ) + }) + }) describe('Should succeed only with widenet service', () => { it('should fulfill with correct address', () => { @@ -257,21 +257,21 @@ describe('[unit] cep-promise for browser', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/99999999') .replyWithFile( 404, path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ); + ) return cep('5010000').then((address) => expect(address).to.deep.equal({ @@ -282,9 +282,9 @@ describe('[unit] cep-promise for browser', () => { street: 'Rua Caiubi', service: 'widenet', }) - ); - }); - }); + ) + }) + }) describe('Should succeed only with brasilapi service', () => { it('should fulfill with correct address', () => { @@ -293,21 +293,21 @@ describe('[unit] cep-promise for browser', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ); + ) return cep('5010000').then((address) => expect(address).to.deep.equal({ @@ -318,9 +318,9 @@ describe('[unit] cep-promise for browser', () => { street: 'Rua Caiubi', service: 'brasilapi', }) - ); - }); - }); + ) + }) + }) describe('when invoked with an inexistent '99999999' CEP', () => { it('should reject with 'service_error'', () => { @@ -329,27 +329,27 @@ describe('[unit] cep-promise for browser', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/99999-999.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/99999999') .replyWithFile( 404, path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ); + ) nock('https://api.postmon.com.br') .get('/v1/cep/99999999') .replyWithFile( 404, path.join(__dirname, '/fixtures/postmon-cep-99999999-error.json') - ); + ) return cep('99999999').catch((error) => { return expect(error) @@ -372,10 +372,10 @@ describe('[unit] cep-promise for browser', () => { service: 'postmon', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when invoked with an invalid '123456789' CEP', () => { it('should reject with 'validation_error'', () => { @@ -392,27 +392,27 @@ describe('[unit] cep-promise for browser', () => { message: 'CEP informado possui mais do que 8 caracteres.', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when http request fails both for all services with bad response', () => { it('should reject with 'service_error'', () => { nock('https://viacep.com.br') .get('/ws/05010000/json/') - .reply(400, '

Bad Request (400)

'); + .reply(400, '

Bad Request (400)

') nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') - .reply(400, '

Bad Request (400)

'); + .reply(400, '

Bad Request (400)

') nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') - .reply(400, '

Bad Request (400)

'); + .reply(400, '

Bad Request (400)

') nock('https://api.postmon.com.br') .get('/v1/cep/05010000') - .reply(400, '

Bad Request (400)

'); + .reply(400, '

Bad Request (400)

') return cep('05010000').catch((error) => { return expect(error) @@ -440,16 +440,16 @@ describe('[unit] cep-promise for browser', () => { service: 'brasilapi', }, ], - }); - }); - }); - }); + }) + }) + }) + }) afterEach(() => { - nock.cleanAll(); - }); + nock.cleanAll() + }) after(() => { - delete global.window; - }); -}); + delete global.window + }) +}) diff --git a/test/unit/cep-promise-node.spec.js b/test/unit/cep-promise-node.spec.js index 761e1c66..ad9b5e9c 100644 --- a/test/unit/cep-promise-node.spec.js +++ b/test/unit/cep-promise-node.spec.js @@ -1,29 +1,29 @@ -'use strict'; +'use strict' -import chai from 'chai'; -import chaiAsPromised from 'chai-as-promised'; -import chaiSubset from 'chai-subset'; -import nock from 'nock'; -import path from 'path'; +import chai from 'chai' +import chaiAsPromised from 'chai-as-promised' +import chaiSubset from 'chai-subset' +import nock from 'nock' +import path from 'path' -import cep from '../../src/cep-promise.js'; -import CepPromiseError from '../../src/errors/cep-promise.js'; +import cep from '../../src/cep-promise.js' +import CepPromiseError from '../../src/errors/cep-promise.js' -chai.use(chaiAsPromised); -chai.use(chaiSubset); +chai.use(chaiAsPromised) +chai.use(chaiSubset) -let expect = chai.expect; +let expect = chai.expect describe('[unit] cep-promise for node', () => { before(() => { - nock.disableNetConnect(); - }); + nock.disableNetConnect() + }) describe('when imported', () => { it('should return a Function', () => { - expect(cep).to.be.a('function'); - }); - }); + expect(cep).to.be.a('function') + }) + }) describe('when invoked', () => { it('should return a Promise', () => { @@ -32,47 +32,47 @@ describe('[unit] cep-promise for node', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ); + ) nock('https://api.postmon.com.br') .get('/v1/cep/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') - ); + ) - const cepPromise = cep('05010000'); - expect(cepPromise.then).to.be.a('function'); - expect(cepPromise.catch).to.be.a('function'); - }); - }); + const cepPromise = cep('05010000') + expect(cepPromise.then).to.be.a('function') + expect(cepPromise.catch).to.be.a('function') + }) + }) describe('when invoked without arguments', () => { it('should reject with 'validation_error'', () => { @@ -90,10 +90,10 @@ describe('[unit] cep-promise for node', () => { service: 'cep_validation', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when invoked with an Array', () => { it('should reject with 'validation_error'', () => { @@ -111,10 +111,10 @@ describe('[unit] cep-promise for node', () => { service: 'cep_validation', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when invoked with an Object', () => { it('should reject with 'validation_error'', () => { @@ -132,15 +132,15 @@ describe('[unit] cep-promise for node', () => { service: 'cep_validation', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when invoked with an Function', () => { it('should reject with 'validation_error'', () => { return cep(function zelda() { - return 'link'; + return 'link' }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -155,10 +155,10 @@ describe('[unit] cep-promise for node', () => { service: 'cep_validation', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when invoked with a valid '05010000' String', () => { it('should fulfill with correct address', () => { @@ -167,35 +167,35 @@ describe('[unit] cep-promise for node', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ); + ) return cep('05010000').then((address) => expect(address).to.deep.equal({ @@ -206,9 +206,9 @@ describe('[unit] cep-promise for node', () => { street: 'Rua Caiubi', service: address.service, }) - ); - }); - }); + ) + }) + }) describe('when invoked with a valid 5010000 Number', () => { it('should fulfill with correct address', () => { @@ -217,35 +217,35 @@ describe('[unit] cep-promise for node', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ); + ) return cep(5010000).then((address) => expect(address).to.deep.equal({ @@ -256,9 +256,9 @@ describe('[unit] cep-promise for node', () => { street: 'Rua Caiubi', service: address.service, }) - ); - }); - }); + ) + }) + }) describe('Should succeed only with correios service', () => { it('should fulfill with correct address', () => { @@ -267,35 +267,35 @@ describe('[unit] cep-promise for node', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') - ); + ) nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ); + ) nock('https://cep.widenet.host') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/99999999') .replyWithFile( 404, path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ); + ) return cep('05010000').then((address) => expect(address).to.deep.equal({ @@ -306,9 +306,9 @@ describe('[unit] cep-promise for node', () => { street: 'Rua Caiubi', service: 'correios', }) - ); - }); - }); + ) + }) + }) describe('Should succeed only with correios-alt service', () => { it('should fulfill with correct address', () => { @@ -317,42 +317,42 @@ describe('[unit] cep-promise for node', () => { .replyWithFile( 500, path.join(__dirname, '/fixtures/response-unknown-format.xml') - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 404, path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ); + ) nock('https://api.postmon.com.br') .get('/v1/cep/05010000') .replyWithFile( 404, path.join(__dirname, '/fixtures/postmon-cep-99999999-error.json') - ); + ) return cep('05010000').then((address) => { expect(address) @@ -363,10 +363,10 @@ describe('[unit] cep-promise for node', () => { neighborhood: 'Perdizes', street: 'Rua Caiubi', service: 'correios-alt', - }); - }); - }); - }); + }) + }) + }) + }) describe('Should succeed only with viacep service', () => { it('should fulfill with correct address', () => { @@ -375,35 +375,35 @@ describe('[unit] cep-promise for node', () => { .replyWithFile( 500, path.join(__dirname, '/fixtures/response-unknown-format.xml') - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') - ); + ) nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/99999999') .replyWithFile( 404, path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ); + ) return cep('05010000').then((address) => expect(address).to.deep.equal({ @@ -414,9 +414,9 @@ describe('[unit] cep-promise for node', () => { street: 'Rua Caiubi', service: 'viacep', }) - ); - }); - }); + ) + }) + }) describe('Should succeed only with widenet service', () => { it('should fulfill with correct address', () => { @@ -425,35 +425,35 @@ describe('[unit] cep-promise for node', () => { .replyWithFile( 500, path.join(__dirname, '/fixtures/response-unknown-format.xml') - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') - ); + ) nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/99999999') .replyWithFile( 404, path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ); + ) return cep('5010000').then((address) => expect(address).to.deep.equal({ @@ -464,9 +464,9 @@ describe('[unit] cep-promise for node', () => { street: 'Rua Caiubi', service: 'widenet', }) - ); - }); - }); + ) + }) + }) describe('Should succeed only with brasilapi service', () => { it('should fulfill with correct address', () => { @@ -475,35 +475,35 @@ describe('[unit] cep-promise for node', () => { .replyWithFile( 500, path.join(__dirname, '/fixtures/response-unknown-format.xml') - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') - ); + ) nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ); + ) return cep('5010000').then((address) => expect(address).to.deep.equal({ @@ -514,9 +514,9 @@ describe('[unit] cep-promise for node', () => { street: 'Rua Caiubi', service: 'brasilapi', }) - ); - }); - }); + ) + }) + }) describe('when its not possible to parse the returned XML and then succeed to one failover service', () => { it('should fulfill with correct address', () => { @@ -525,35 +525,35 @@ describe('[unit] cep-promise for node', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-bad-xml.xml') - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ); + ) return cep('5010000').then((address) => expect(address).to.deep.equal({ @@ -564,9 +564,9 @@ describe('[unit] cep-promise for node', () => { street: 'Rua Caiubi', service: address.service, }) - ); - }); - }); + ) + }) + }) describe('when http request to Correios fails and then succeed to the failover service', () => { it('should fulfill with correct address', () => { @@ -574,35 +574,35 @@ describe('[unit] cep-promise for node', () => { .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithError( 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ); + ) return cep('5010000').then((address) => expect(address).to.deep.equal({ @@ -613,9 +613,9 @@ describe('[unit] cep-promise for node', () => { street: 'Rua Caiubi', service: address.service, }) - ); - }); - }); + ) + }) + }) describe('when invoked with an inexistent '99999999' CEP', () => { it('should reject with 'service_error'', () => { @@ -624,42 +624,42 @@ describe('[unit] cep-promise for node', () => { .replyWithFile( 500, path.join(__dirname, '/fixtures/response-cep-not-found.xml') - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-99999999-error.json') - ); + ) nock('https://viacep.com.br') .get('/ws/99999999/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json') - ); + ) nock('https://api.postmon.com.br') .get('/v1/cep/99999999') .replyWithFile( 404, path.join(__dirname, '/fixtures/postmon-cep-99999999-error.json') - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/99999-999.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-99999999-error.json') - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/99999999') .replyWithFile( 404, path.join(__dirname, '/fixtures/brasilapi-cep-99999999-error.json') - ); + ) return cep('99999999').catch((error) => { return expect(error) @@ -690,10 +690,10 @@ describe('[unit] cep-promise for node', () => { service: 'postmon', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when invoked with an invalid '123456789' CEP', () => { it('should reject with 'validation_error'', () => { @@ -710,10 +710,10 @@ describe('[unit] cep-promise for node', () => { message: 'CEP informado possui mais do que 8 caracteres.', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when http request fails both for primary and secondary service with bad response', () => { it('should reject with 'service_error'', () => { @@ -721,23 +721,23 @@ describe('[unit] cep-promise for node', () => { .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithError( 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') - .reply(400, '

Bad Request (400)

'); + .reply(400, '

Bad Request (400)

') nock('https://viacep.com.br') .get('/ws/05010000/json/') - .reply(400, '

Bad Request (400)

'); + .reply(400, '

Bad Request (400)

') nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') - .reply(400, '

Bad Request (400)

'); + .reply(400, '

Bad Request (400)

') nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') - .reply(400, '

Bad Request (400)

'); + .reply(400, '

Bad Request (400)

') return cep('05010000').catch((error) => { return expect(error) @@ -769,10 +769,10 @@ describe('[unit] cep-promise for node', () => { service: 'brasilapi', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when http request has unformatted xml and alternatives services fails', () => { it('should reject with 'service_error'', () => { @@ -781,23 +781,23 @@ describe('[unit] cep-promise for node', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-bad-xml.xml') - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') - .reply(200, { erro: true }); + .reply(200, { erro: true }) nock('https://viacep.com.br') .get('/ws/05010000/json/') - .reply(400, '

Bad Request (400)

'); + .reply(400, '

Bad Request (400)

') nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') - .reply(400, '

Bad Request (400)

'); + .reply(400, '

Bad Request (400)

') nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') - .reply(400, '

Bad Request (400)

'); + .reply(400, '

Bad Request (400)

') return cep('05010000').catch((error) => { return expect(error) @@ -829,10 +829,10 @@ describe('[unit] cep-promise for node', () => { service: 'brasilapi', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('when http request fails both for primary and secondary service with error', () => { it('should reject with 'service_error'', () => { @@ -840,29 +840,29 @@ describe('[unit] cep-promise for node', () => { .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithError( 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ); + ) nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') - .reply(200, { erro: true }); + .reply(200, { erro: true }) nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithError( 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ); + ) nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithError( 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ); + ) nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithError( 'getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443' - ); + ) return cep('05010000').catch((error) => { return expect(error) @@ -893,12 +893,12 @@ describe('[unit] cep-promise for node', () => { service: 'brasilapi', }, ], - }); - }); - }); - }); + }) + }) + }) + }) afterEach(() => { - nock.cleanAll(); - }); -}); + nock.cleanAll() + }) +}) diff --git a/test/unit/cep-promise-providers.spec.js b/test/unit/cep-promise-providers.spec.js index a5d2ddaa..69a63b07 100644 --- a/test/unit/cep-promise-providers.spec.js +++ b/test/unit/cep-promise-providers.spec.js @@ -1,22 +1,22 @@ -'use strict'; +'use strict' -import chai from 'chai'; -import chaiSubset from 'chai-subset'; -import nock from 'nock'; -import path from 'path'; +import chai from 'chai' +import chaiSubset from 'chai-subset' +import nock from 'nock' +import path from 'path' -import cep from '../../src/cep-promise.js'; -import CepPromiseError from '../../src/errors/cep-promise.js'; -import { getAvailableServices } from '../../src/services/index.js'; +import cep from '../../src/cep-promise.js' +import CepPromiseError from '../../src/errors/cep-promise.js' +import { getAvailableServices } from '../../src/services/index.js' -chai.use(chaiSubset); +chai.use(chaiSubset) -let expect = chai.expect; +let expect = chai.expect describe('when invoked with providers parameter', () => { before(() => { - nock.disableNetConnect(); - }); + nock.disableNetConnect() + }) describe('and the providers param is a string', () => { it('should reject with 'validation_error'', () => { @@ -33,10 +33,10 @@ describe('when invoked with providers parameter', () => { message: 'O parâmetro providers deve ser uma lista.', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('and the providers param is a integer', () => { it('should reject with 'validation_error'', () => { @@ -53,10 +53,10 @@ describe('when invoked with providers parameter', () => { message: 'O parâmetro providers deve ser uma lista.', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('and the providers param is a object', () => { it('should reject with 'validation_error'', () => { @@ -73,10 +73,10 @@ describe('when invoked with providers parameter', () => { message: 'O parâmetro providers deve ser uma lista.', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('and the providers param is a function', () => { it('should reject with 'validation_error'', () => { @@ -93,14 +93,14 @@ describe('when invoked with providers parameter', () => { message: 'O parâmetro providers deve ser uma lista.', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('and the providers param is a invalid array', () => { it('should reject with 'validation_error'', () => { - const availableProviders = Object.keys(getAvailableServices()); + const availableProviders = Object.keys(getAvailableServices()) return cep('05010000', { providers: [123, 'viacep'] }).catch((error) => { return expect(error) @@ -116,10 +116,10 @@ describe('when invoked with providers parameter', () => { service: 'providers_validation', }, ], - }); - }); - }); - }); + }) + }) + }) + }) describe('and the providers param is ['viacep']', () => { it('should call only viacep service', () => { @@ -128,34 +128,34 @@ describe('when invoked with providers parameter', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) const correiosAltMock = nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) const viaCepMock = nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) const postmonMock = nock('https://api.postmon.com.br') .get('/v1/cep/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') - ); + ) const wideNetMock = nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) return cep('05010000', { providers: ['viacep'] }).then((address) => { expect(address).to.deep.equal({ @@ -165,16 +165,16 @@ describe('when invoked with providers parameter', () => { neighborhood: 'Perdizes', street: 'Rua Caiubi', service: 'viacep', - }); + }) - expect(viaCepMock.isDone()).to.be.equal(true); - expect(correiosMock.isDone()).to.be.equal(false); - expect(correiosAltMock.isDone()).to.be.equal(false); - expect(wideNetMock.isDone()).to.be.equal(false); - expect(postmonMock.isDone()).to.be.equal(false); - }); - }); - }); + expect(viaCepMock.isDone()).to.be.equal(true) + expect(correiosMock.isDone()).to.be.equal(false) + expect(correiosAltMock.isDone()).to.be.equal(false) + expect(wideNetMock.isDone()).to.be.equal(false) + expect(postmonMock.isDone()).to.be.equal(false) + }) + }) + }) describe('and the providers param is ['postmon']', () => { it('should call only postmon service', () => { @@ -183,34 +183,34 @@ describe('when invoked with providers parameter', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) const correiosAltMock = nock('https://buscacepinter.correios.com.br') .post('/app/cep/carrega-cep.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) const viaCepMock = nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) const postmonMock = nock('https://api.postmon.com.br') .get('/v1/cep/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') - ); + ) const wideNetMock = nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) return cep('05010000', { providers: ['postmon'] }).then((address) => { expect(address).to.deep.equal({ @@ -220,16 +220,16 @@ describe('when invoked with providers parameter', () => { neighborhood: 'Perdizes', street: 'Rua Caiubi', service: 'postmon', - }); + }) - expect(viaCepMock.isDone()).to.be.equal(false); - expect(correiosMock.isDone()).to.be.equal(false); - expect(correiosAltMock.isDone()).to.be.equal(false); - expect(wideNetMock.isDone()).to.be.equal(false); - expect(postmonMock.isDone()).to.be.equal(true); - }); - }); - }); + expect(viaCepMock.isDone()).to.be.equal(false) + expect(correiosMock.isDone()).to.be.equal(false) + expect(correiosAltMock.isDone()).to.be.equal(false) + expect(wideNetMock.isDone()).to.be.equal(false) + expect(postmonMock.isDone()).to.be.equal(true) + }) + }) + }) describe('and the providers param is ['widenet']', () => { it('should call only widenet service', () => { @@ -238,34 +238,34 @@ describe('when invoked with providers parameter', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) const correiosAltMock = nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) const viaCepMock = nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) const wideNetMock = nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) const postmonMock = nock('https://api.postmon.com.br') .get('/v1/cep/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') - ); + ) return cep('05010000', { providers: ['widenet'] }).then((address) => { expect(address).to.deep.equal({ @@ -275,16 +275,16 @@ describe('when invoked with providers parameter', () => { neighborhood: 'Perdizes', street: 'Rua Caiubi', service: 'widenet', - }); + }) - expect(wideNetMock.isDone()).to.be.equal(true); - expect(viaCepMock.isDone()).to.be.equal(false); - expect(correiosMock.isDone()).to.be.equal(false); - expect(correiosAltMock.isDone()).to.be.equal(false); - expect(postmonMock.isDone()).to.be.equal(false); - }); - }); - }); + expect(wideNetMock.isDone()).to.be.equal(true) + expect(viaCepMock.isDone()).to.be.equal(false) + expect(correiosMock.isDone()).to.be.equal(false) + expect(correiosAltMock.isDone()).to.be.equal(false) + expect(postmonMock.isDone()).to.be.equal(false) + }) + }) + }) describe('and the providers param is ['correios']', () => { it('should call only correios service', () => { @@ -293,34 +293,34 @@ describe('when invoked with providers parameter', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) const postmonMock = nock('https://api.postmon.com.br') .get('/v1/cep/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') - ); + ) const correiosAltMock = nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) const viaCepMock = nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) const wideNetMock = nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) return cep('05010000', { providers: ['correios'] }).then((address) => { expect(address).to.deep.equal({ @@ -330,16 +330,16 @@ describe('when invoked with providers parameter', () => { neighborhood: 'Perdizes', street: 'Rua Caiubi', service: 'correios', - }); + }) - expect(correiosMock.isDone()).to.be.equal(true); - expect(correiosAltMock.isDone()).to.be.equal(false); - expect(viaCepMock.isDone()).to.be.equal(false); - expect(wideNetMock.isDone()).to.be.equal(false); - expect(postmonMock.isDone()).to.be.equal(false); - }); - }); - }); + expect(correiosMock.isDone()).to.be.equal(true) + expect(correiosAltMock.isDone()).to.be.equal(false) + expect(viaCepMock.isDone()).to.be.equal(false) + expect(wideNetMock.isDone()).to.be.equal(false) + expect(postmonMock.isDone()).to.be.equal(false) + }) + }) + }) describe('and the providers param is ['correios-alt']', () => { it('should call only correios alt service', () => { @@ -348,34 +348,34 @@ describe('when invoked with providers parameter', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) const postmonMock = nock('https://api.postmon.com.br') .get('/v1/cep/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') - ); + ) const correiosAltMock = nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) const viaCepMock = nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) const wideNetMock = nock('https://cep.widenet.host') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) return cep('05010000', { providers: ['correios-alt'] }).then( (address) => { @@ -386,17 +386,17 @@ describe('when invoked with providers parameter', () => { neighborhood: 'Perdizes', street: 'Rua Caiubi', service: 'correios-alt', - }); + }) - expect(correiosMock.isDone()).to.be.equal(false); - expect(correiosAltMock.isDone()).to.be.equal(true); - expect(viaCepMock.isDone()).to.be.equal(false); - expect(wideNetMock.isDone()).to.be.equal(false); - expect(postmonMock.isDone()).to.be.equal(false); + expect(correiosMock.isDone()).to.be.equal(false) + expect(correiosAltMock.isDone()).to.be.equal(true) + expect(viaCepMock.isDone()).to.be.equal(false) + expect(wideNetMock.isDone()).to.be.equal(false) + expect(postmonMock.isDone()).to.be.equal(false) } - ); - }); - }); + ) + }) + }) describe('and the providers param is ['brasilapi']', () => { it('should call only brasilapi service', () => { @@ -405,42 +405,42 @@ describe('when invoked with providers parameter', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) const correiosAltMock = nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) const postmonMock = nock('https://api.postmon.com.br') .get('/v1/cep/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') - ); + ) const viaCepMock = nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) const wideNetMock = nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) const brasilAPIMock = nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/brasilapi-cep-05010000-found.json') - ); + ) return cep('05010000', { providers: ['brasilapi'] }).then((address) => { expect(address).to.deep.equal({ @@ -450,17 +450,17 @@ describe('when invoked with providers parameter', () => { neighborhood: 'Perdizes', street: 'Rua Caiubi', service: 'brasilapi', - }); - - expect(correiosMock.isDone()).to.be.equal(false); - expect(correiosAltMock.isDone()).to.be.equal(false); - expect(viaCepMock.isDone()).to.be.equal(false); - expect(wideNetMock.isDone()).to.be.equal(false); - expect(postmonMock.isDone()).to.be.equal(false); - expect(brasilAPIMock.isDone()).to.be.equal(true); - }); - }); - }); + }) + + expect(correiosMock.isDone()).to.be.equal(false) + expect(correiosAltMock.isDone()).to.be.equal(false) + expect(viaCepMock.isDone()).to.be.equal(false) + expect(wideNetMock.isDone()).to.be.equal(false) + expect(postmonMock.isDone()).to.be.equal(false) + expect(brasilAPIMock.isDone()).to.be.equal(true) + }) + }) + }) describe('and the providers param is ['correios, viacep']', () => { it('should call only correios and viacep services', () => { @@ -469,35 +469,35 @@ describe('when invoked with providers parameter', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) const correiosAltMock = nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) const viaCepMock = nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) const wideNetMock = nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) const postmonMock = nock('https://api.postmon.com.br') .get('/v1/cep/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') - ); + ) return cep('05010000', { providers: ['correios', 'viacep'] }).then( (address) => { @@ -508,17 +508,17 @@ describe('when invoked with providers parameter', () => { neighborhood: 'Perdizes', street: 'Rua Caiubi', service: address.service, - }); + }) - expect(viaCepMock.isDone()).to.be.equal(true); - expect(correiosMock.isDone()).to.be.equal(true); - expect(correiosAltMock.isDone()).to.be.equal(false); - expect(wideNetMock.isDone()).to.be.equal(false); - expect(postmonMock.isDone()).to.be.equal(false); + expect(viaCepMock.isDone()).to.be.equal(true) + expect(correiosMock.isDone()).to.be.equal(true) + expect(correiosAltMock.isDone()).to.be.equal(false) + expect(wideNetMock.isDone()).to.be.equal(false) + expect(postmonMock.isDone()).to.be.equal(false) } - ); - }); - }); + ) + }) + }) describe('and the providers param is []', () => { it('should call all services', () => { @@ -527,35 +527,35 @@ describe('when invoked with providers parameter', () => { .replyWithFile( 200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml') - ); + ) const correiosAltMock = nock('https://buscacepinter.correios.com.br') .post('/app/endereco/carrega-cep-endereco.php') .replyWithFile( 200, path.join(__dirname, '/fixtures/correios-alt-cep-05010000-found.json') - ); + ) const postmonMock = nock('https://api.postmon.com.br') .get('/v1/cep/05010000') .replyWithFile( 200, path.join(__dirname, '/fixtures/postmon-cep-05010000-found.json') - ); + ) const viaCepMock = nock('https://viacep.com.br') .get('/ws/05010000/json/') .replyWithFile( 200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json') - ); + ) const wideNetMock = nock('https://cdn.apicep.com') .get('/file/apicep/05010-000.json') .replyWithFile( 200, path.join(__dirname, '/fixtures/widenet-cep-05010000-found.json') - ); + ) return cep('05010000', { providers: [] }).then((address) => { expect(address).to.deep.equal({ @@ -565,18 +565,18 @@ describe('when invoked with providers parameter', () => { neighborhood: 'Perdizes', street: 'Rua Caiubi', service: address.service, - }); + }) - expect(viaCepMock.isDone()).to.be.equal(true); - expect(correiosMock.isDone()).to.be.equal(true); - expect(correiosAltMock.isDone()).to.be.equal(true); - expect(wideNetMock.isDone()).to.be.equal(true); - expect(postmonMock.isDone()).to.be.equal(true); - }); - }); - }); + expect(viaCepMock.isDone()).to.be.equal(true) + expect(correiosMock.isDone()).to.be.equal(true) + expect(correiosAltMock.isDone()).to.be.equal(true) + expect(wideNetMock.isDone()).to.be.equal(true) + expect(postmonMock.isDone()).to.be.equal(true) + }) + }) + }) afterEach(() => { - nock.cleanAll(); - }); -}); + nock.cleanAll() + }) +}) From 4ef53e116e0914ea21e38139efd376465240b4e0 Mon Sep 17 00:00:00 2001 From: Rodrigo Teixeira Andreotti Date: Thu, 28 Mar 2024 19:20:47 -0300 Subject: [PATCH 09/10] Fix quotes --- test/e2e/cep-promise.spec.js | 10 +++++----- test/unit/cep-promise-browser.spec.js | 20 ++++++++++---------- test/unit/cep-promise-node.spec.js | 24 ++++++++++++------------ test/unit/cep-promise-providers.spec.js | 24 ++++++++++++------------ test/unit/cep-promise-timeout.spec.js | 2 +- 5 files changed, 40 insertions(+), 40 deletions(-) diff --git a/test/e2e/cep-promise.spec.js b/test/e2e/cep-promise.spec.js index 292c6134..7d77b042 100644 --- a/test/e2e/cep-promise.spec.js +++ b/test/e2e/cep-promise.spec.js @@ -18,7 +18,7 @@ describe('[e2e] cep-promise', () => { nock.enableNetConnect() }) - describe('when invoked with a valid '05010000' string', () => { + describe('when invoked with a valid "05010000" string', () => { it('should fulfill with correct address', () => cep('05010000').then((address) => { expect(address).to.deep.equal({ @@ -47,8 +47,8 @@ describe('[e2e] cep-promise', () => { }) }) - describe('when invoked with an inexistent '99999999' CEP', () => { - it('should reject with 'service_error'', () => { + describe('when invoked with an inexistent "99999999" CEP', () => { + it('should reject with "service_error"', () => { return cep('99999999').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -87,8 +87,8 @@ describe('[e2e] cep-promise', () => { }) }) - describe('when invoked with an invalid '123456789' CEP', () => { - it('should reject with 'validation_error'', () => { + describe('when invoked with an invalid "123456789" CEP', () => { + it('should reject with "validation_error"', () => { return cep('123456789').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) diff --git a/test/unit/cep-promise-browser.spec.js b/test/unit/cep-promise-browser.spec.js index 7eadcd3e..444c8057 100644 --- a/test/unit/cep-promise-browser.spec.js +++ b/test/unit/cep-promise-browser.spec.js @@ -57,7 +57,7 @@ describe('[unit] cep-promise for browser', () => { }) describe('when invoked without arguments', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep().catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -78,7 +78,7 @@ describe('[unit] cep-promise for browser', () => { }) describe('when invoked with an Array', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep([1, 2, 3]).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -99,7 +99,7 @@ describe('[unit] cep-promise for browser', () => { }) describe('when invoked with an Object', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep({ nintendo: true, ps: false, xbox: false }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -120,7 +120,7 @@ describe('[unit] cep-promise for browser', () => { }) describe('when invoked with an Function', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep(function zelda() { return 'link' }).catch((error) => { @@ -142,7 +142,7 @@ describe('[unit] cep-promise for browser', () => { }) }) - describe('when invoked with a valid '05010000' String', () => { + describe('when invoked with a valid "05010000" String', () => { it('should fulfill with correct address', () => { nock('https://viacep.com.br') .get('/ws/05010000/json/') @@ -322,8 +322,8 @@ describe('[unit] cep-promise for browser', () => { }) }) - describe('when invoked with an inexistent '99999999' CEP', () => { - it('should reject with 'service_error'', () => { + describe('when invoked with an inexistent "99999999" CEP', () => { + it('should reject with "service_error"', () => { nock('https://viacep.com.br') .get('/ws/99999999/json/') .replyWithFile( @@ -377,8 +377,8 @@ describe('[unit] cep-promise for browser', () => { }) }) - describe('when invoked with an invalid '123456789' CEP', () => { - it('should reject with 'validation_error'', () => { + describe('when invoked with an invalid "123456789" CEP', () => { + it('should reject with "validation_error"', () => { return cep('123456789').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -398,7 +398,7 @@ describe('[unit] cep-promise for browser', () => { }) describe('when http request fails both for all services with bad response', () => { - it('should reject with 'service_error'', () => { + it('should reject with "service_error"', () => { nock('https://viacep.com.br') .get('/ws/05010000/json/') .reply(400, '

Bad Request (400)

') diff --git a/test/unit/cep-promise-node.spec.js b/test/unit/cep-promise-node.spec.js index ad9b5e9c..39ba682c 100644 --- a/test/unit/cep-promise-node.spec.js +++ b/test/unit/cep-promise-node.spec.js @@ -75,7 +75,7 @@ describe('[unit] cep-promise for node', () => { }) describe('when invoked without arguments', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep().catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -96,7 +96,7 @@ describe('[unit] cep-promise for node', () => { }) describe('when invoked with an Array', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep([1, 2, 3]).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -117,7 +117,7 @@ describe('[unit] cep-promise for node', () => { }) describe('when invoked with an Object', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep({ nintendo: true, ps: false, xbox: false }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -138,7 +138,7 @@ describe('[unit] cep-promise for node', () => { }) describe('when invoked with an Function', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep(function zelda() { return 'link' }).catch((error) => { @@ -160,7 +160,7 @@ describe('[unit] cep-promise for node', () => { }) }) - describe('when invoked with a valid '05010000' String', () => { + describe('when invoked with a valid "05010000" String', () => { it('should fulfill with correct address', () => { nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') @@ -617,8 +617,8 @@ describe('[unit] cep-promise for node', () => { }) }) - describe('when invoked with an inexistent '99999999' CEP', () => { - it('should reject with 'service_error'', () => { + describe('when invoked with an inexistent "99999999" CEP', () => { + it('should reject with "service_error"', () => { nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( @@ -695,8 +695,8 @@ describe('[unit] cep-promise for node', () => { }) }) - describe('when invoked with an invalid '123456789' CEP', () => { - it('should reject with 'validation_error'', () => { + describe('when invoked with an invalid "123456789" CEP', () => { + it('should reject with "validation_error"', () => { return cep('123456789').catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -716,7 +716,7 @@ describe('[unit] cep-promise for node', () => { }) describe('when http request fails both for primary and secondary service with bad response', () => { - it('should reject with 'service_error'', () => { + it('should reject with "service_error"', () => { nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithError( @@ -775,7 +775,7 @@ describe('[unit] cep-promise for node', () => { }) describe('when http request has unformatted xml and alternatives services fails', () => { - it('should reject with 'service_error'', () => { + it('should reject with "service_error"', () => { nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithFile( @@ -835,7 +835,7 @@ describe('[unit] cep-promise for node', () => { }) describe('when http request fails both for primary and secondary service with error', () => { - it('should reject with 'service_error'', () => { + it('should reject with "service_error"', () => { nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') .replyWithError( diff --git a/test/unit/cep-promise-providers.spec.js b/test/unit/cep-promise-providers.spec.js index 69a63b07..b68aa324 100644 --- a/test/unit/cep-promise-providers.spec.js +++ b/test/unit/cep-promise-providers.spec.js @@ -19,7 +19,7 @@ describe('when invoked with providers parameter', () => { }) describe('and the providers param is a string', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep('05010000', { providers: 'viacep' }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -39,7 +39,7 @@ describe('when invoked with providers parameter', () => { }) describe('and the providers param is a integer', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep('05010000', { providers: 123 }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -59,7 +59,7 @@ describe('when invoked with providers parameter', () => { }) describe('and the providers param is a object', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep('05010000', { providers: {} }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -79,7 +79,7 @@ describe('when invoked with providers parameter', () => { }) describe('and the providers param is a function', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { return cep('05010000', { providers: () => () => {} }).catch((error) => { return expect(error) .to.be.an.instanceOf(CepPromiseError) @@ -99,7 +99,7 @@ describe('when invoked with providers parameter', () => { }) describe('and the providers param is a invalid array', () => { - it('should reject with 'validation_error'', () => { + it('should reject with "validation_error"', () => { const availableProviders = Object.keys(getAvailableServices()) return cep('05010000', { providers: [123, 'viacep'] }).catch((error) => { @@ -121,7 +121,7 @@ describe('when invoked with providers parameter', () => { }) }) - describe('and the providers param is ['viacep']', () => { + describe('and the providers param is ["viacep"]', () => { it('should call only viacep service', () => { const correiosMock = nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') @@ -176,7 +176,7 @@ describe('when invoked with providers parameter', () => { }) }) - describe('and the providers param is ['postmon']', () => { + describe('and the providers param is ["postmon"]', () => { it('should call only postmon service', () => { const correiosMock = nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') @@ -231,7 +231,7 @@ describe('when invoked with providers parameter', () => { }) }) - describe('and the providers param is ['widenet']', () => { + describe('and the providers param is ["widenet"]', () => { it('should call only widenet service', () => { const correiosMock = nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') @@ -286,7 +286,7 @@ describe('when invoked with providers parameter', () => { }) }) - describe('and the providers param is ['correios']', () => { + describe('and the providers param is ["correios"]', () => { it('should call only correios service', () => { const correiosMock = nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') @@ -341,7 +341,7 @@ describe('when invoked with providers parameter', () => { }) }) - describe('and the providers param is ['correios-alt']', () => { + describe('and the providers param is ["correios-alt"]', () => { it('should call only correios alt service', () => { const correiosMock = nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') @@ -398,7 +398,7 @@ describe('when invoked with providers parameter', () => { }) }) - describe('and the providers param is ['brasilapi']', () => { + describe('and the providers param is ["brasilapi"]', () => { it('should call only brasilapi service', () => { const correiosMock = nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') @@ -462,7 +462,7 @@ describe('when invoked with providers parameter', () => { }) }) - describe('and the providers param is ['correios, viacep']', () => { + describe('and the providers param is ["correios, viacep"]', () => { it('should call only correios and viacep services', () => { const correiosMock = nock('https://apps.correios.com.br') .post('/SigepMasterJPA/AtendeClienteService/AtendeCliente') diff --git a/test/unit/cep-promise-timeout.spec.js b/test/unit/cep-promise-timeout.spec.js index b76f9aa6..910af40a 100644 --- a/test/unit/cep-promise-timeout.spec.js +++ b/test/unit/cep-promise-timeout.spec.js @@ -18,7 +18,7 @@ describe('when invoked with timeout parameter', () => { }) describe('and the providers exceed the timeout', () => { - it('should reject with 'service_error'', () => { + it('should reject with "service_error"', () => { nock('https://brasilapi.com.br/') .get('/api/cep/v1/05010000') .delay(3) From 73d4e9a6ecdf5751c0ad43eb0d3cfaceb7b2f8fb Mon Sep 17 00:00:00 2001 From: Rodrigo Teixeira Andreotti Date: Thu, 28 Mar 2024 19:32:33 -0300 Subject: [PATCH 10/10] Fix tests --- test/unit/cep-promise-providers.spec.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/unit/cep-promise-providers.spec.js b/test/unit/cep-promise-providers.spec.js index b68aa324..8cb55279 100644 --- a/test/unit/cep-promise-providers.spec.js +++ b/test/unit/cep-promise-providers.spec.js @@ -110,9 +110,9 @@ describe('when invoked with providers parameter', () => { type: 'validation_error', errors: [ { - message: `O provider '123' é inválido. Os providers disponíveis são: ['${availableProviders.join( - '', '' - )}'].`, + message: `O provider "123" é inválido. Os providers disponíveis são: ["${availableProviders.join( + '", "' + )}"].`, service: 'providers_validation', }, ],