diff --git a/README.md b/README.md index a2553d8..8c91f43 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,36 @@ cep('05010000') // } ``` +### Realizando uma consulta avançada +Para passar configurações como Proxy, Agent, timeout: + +``` js +import cep from 'cep-promise' +import https from 'https' + +const agent = new https.Agent({ keepAlive: true }) +const proxyURL = 'socks5://127.0.0.1:1950' + +const configurations = { + agent, + proxyURL, + brasilapi: { + timeout:1000 + } +} + +cep('05010000', configurations) + .then(console.log) + + // { + // "cep": "05010000", + // "state": "SP", + // "city": "São Paulo", + // "street": "Rua Caiubí", + // "neighborhood": "Perdizes", + // } +``` + ### Você também poderá passar o CEP como Inteiro diff --git a/rollup.config.js b/rollup.config.js index 74401a3..d83e4c1 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -27,7 +27,7 @@ export default [ input, plugins: [ replace({ - 'node-fetch': 'unfetch', + 'node-fetch': 'unfetch' }) ].concat(defaultPlugins, [ resolve({ @@ -43,4 +43,3 @@ export default [ } } ] - diff --git a/src/cep-promise.js b/src/cep-promise.js index 62588f0..68cbb8d 100644 --- a/src/cep-promise.js +++ b/src/cep-promise.js @@ -26,7 +26,7 @@ export default function (cepRawValue, configurations = {}) { } function validateProviders (providers) { - let availableProviders = Object.keys(getAvailableServices()) + const availableProviders = Object.keys(getAvailableServices()) if (!Array.isArray(providers)) { throw new CepPromiseError({ @@ -35,7 +35,7 @@ function validateProviders (providers) { errors: [ { message: - `O parâmetro providers deve ser uma lista.`, + 'O parâmetro providers deve ser uma lista.', service: 'providers_validation' } ] @@ -107,17 +107,32 @@ function validateInputLength (cepWithLeftPad) { } function fetchCepFromServices (cepWithLeftPad, configurations) { - let providersServices = getAvailableServices() + const providersServices = getAvailableServices() - if (configurations.providers.length === 0) { + const { providers: providersFromConfigurations, ...configurationsWithoutProviders } = configurations + + const providersName = Object.keys(providersServices) + const { globalConfigs, specificConfigs } = Object.entries(configurationsWithoutProviders).reduce((obj, [key, value]) => { + const isAProvider = providersName.includes(key) + + if (isAProvider) { + obj.specificConfigs[key] = value + } else { + obj.globalConfigs[key] = value + } + + return obj + }, { globalConfigs: {}, specificConfigs: {} }) + + if (providersFromConfigurations.length === 0) { return Promise.any( - Object.values(providersServices).map(provider => provider(cepWithLeftPad, configurations)) + Object.entries(providersServices).map(([providerName, provider]) => provider(cepWithLeftPad, { ...globalConfigs, ...specificConfigs[providerName] })) ) } return Promise.any( - configurations.providers.map(provider => { - return providersServices[provider](cepWithLeftPad, configurations) + providersFromConfigurations.map(provider => { + return providersServices[provider](cepWithLeftPad, { ...globalConfigs, ...specificConfigs[provider] }) }) ) } diff --git a/src/services/brasilapi.js b/src/services/brasilapi.js index d3ffba9..0e87571 100644 --- a/src/services/brasilapi.js +++ b/src/services/brasilapi.js @@ -3,15 +3,17 @@ import fetch from 'node-fetch' import ServiceError from '../errors/service.js' -export default function fetchBrasilAPIService (cepWithLeftPad, configurations) { +export default function fetchBrasilAPIService (cepWithLeftPad, { agent = undefined, timeout = undefined, headers = {} }) { const url = `https://brasilapi.com.br/api/cep/v1/${cepWithLeftPad}` const options = { method: 'GET', mode: 'cors', headers: { - 'content-type': 'application/json;charset=utf-8' + 'content-type': 'application/json;charset=utf-8', + ...headers }, - timeout: configurations.timeout || 30000 + agent, + timeout: timeout || 30000 } return fetch(url, options) diff --git a/src/services/correios.js b/src/services/correios.js index acf9591..33b3817 100644 --- a/src/services/correios.js +++ b/src/services/correios.js @@ -3,16 +3,18 @@ import fetch from 'node-fetch' import ServiceError from '../errors/service.js' -export default function fetchCorreiosService (cepWithLeftPad, configurations) { - const url = 'https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente' +export default function fetchCorreiosService (cepWithLeftPad, { proxyURL = '', agent = undefined, timeout = undefined, headers = {} }) { + const url = `https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente` const options = { method: 'POST', body: `<?xml version="1.0"?>\n<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cli="http://cliente.bean.master.sigep.bsb.correios.com.br/">\n <soapenv:Header />\n <soapenv:Body>\n <cli:consultaCEP>\n <cep>${cepWithLeftPad}</cep>\n </cli:consultaCEP>\n </soapenv:Body>\n</soapenv:Envelope>`, headers: { 'Content-Type': 'text/xml;charset=UTF-8', - 'cache-control': 'no-cache' + 'cache-control': 'no-cache', + ...headers }, - timeout: configurations.timeout || 30000 + agent, + timeout: timeout || 30000 } return fetch(url, options) @@ -73,7 +75,7 @@ function extractValuesFromSuccessResponse (xmlObject) { city: xmlObject.cidade, neighborhood: xmlObject.bairro, street: xmlObject.end, - service: 'correios', + service: 'correios' } } diff --git a/src/services/viacep.js b/src/services/viacep.js index 7c3202c..bf805f7 100644 --- a/src/services/viacep.js +++ b/src/services/viacep.js @@ -3,15 +3,17 @@ import fetch from 'node-fetch' import ServiceError from '../errors/service.js' -export default function fetchViaCepService (cepWithLeftPad, configurations) { +export default function fetchViaCepService (cepWithLeftPad, { proxyURL = '', agent = undefined, timeout = undefined, headers = {} }) { const url = `https://viacep.com.br/ws/${cepWithLeftPad}/json/` const options = { method: 'GET', mode: 'cors', headers: { - 'content-type': 'application/json;charset=utf-8' + 'content-type': 'application/json;charset=utf-8', + ...headers }, - timeout: configurations.timeout || 30000 + agent, + timeout: timeout || 30000 } if (typeof window == 'undefined') { @@ -48,7 +50,7 @@ function extractCepValuesFromResponse (responseObject) { city: responseObject.localidade, neighborhood: responseObject.bairro, street: responseObject.logradouro, - service: 'viacep', + service: 'viacep' } } diff --git a/src/services/widenet.js b/src/services/widenet.js index ddfb847..6fa23dd 100644 --- a/src/services/widenet.js +++ b/src/services/widenet.js @@ -3,15 +3,17 @@ import fetch from 'node-fetch' import ServiceError from '../errors/service.js' -export default function fetchWideNetService (cepWithLeftPad, configurations) { +export default function fetchWideNetService (cepWithLeftPad, { proxyURL = '', agent = undefined, timeout = undefined, headers = {} }) { const url = `https://cep.widenet.host/busca-cep/api/cep/${cepWithLeftPad}.json` const options = { method: 'GET', mode: 'cors', headers: { - 'content-type': 'application/json;charset=utf-8' + 'content-type': 'application/json;charset=utf-8', + ...headers }, - timeout: configurations.timeout || 30000 + agent, + timeout : timeout || 30000 } return fetch(url, options) diff --git a/test/e2e/cep-promise.spec.js b/test/e2e/cep-promise.spec.js index f7d9a94..cd09d53 100644 --- a/test/e2e/cep-promise.spec.js +++ b/test/e2e/cep-promise.spec.js @@ -4,6 +4,7 @@ import chai from 'chai' import chaiAsPromised from 'chai-as-promised' import chaiSubset from 'chai-subset' import nock from 'nock' +import https from 'https' import cep from '../../src/cep-promise.js' import CepPromiseError from '../../src/errors/cep-promise.js' @@ -11,7 +12,7 @@ import CepPromiseError from '../../src/errors/cep-promise.js' chai.use(chaiAsPromised) chai.use(chaiSubset) -let expect = chai.expect +const expect = chai.expect describe('[e2e] cep-promise', () => { before(() => { @@ -20,15 +21,16 @@ describe('[e2e] cep-promise', () => { 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 - })}) + .then(address => { + expect(address).to.deep.equal({ + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: address.service + }) + }) ) }) @@ -37,13 +39,30 @@ describe('[e2e] cep-promise', () => { 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 a valid 05010000 number and agent', () => { + it('should fulfill with correct address', async () => { + const agent = new https.Agent({ keepAlive: true }) + + const address = await cep(5010000, { agent }) + + expect(address).to.deep.equal({ + cep: '05010000', + state: 'SP', + city: 'São Paulo', + neighborhood: 'Perdizes', + street: 'Rua Caiubi', + service: address.service + }) }) })