Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,30 @@ cep('05010000')
// }
```

### Realizando uma consulta avançada
Para passar configurações como Proxy e Agent:


``` 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 }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@LorhanSohaky

Aproveitaria este PR e adicionaria novas configurações, como o timeout da requisição, que já foi adicionada pelo @filipedeschamps no PR #190 e também headers, como o User-Agent (para quando rodar do lado do servidor) que eu ajustei no PR #189.

Não esquecer do valor default destas novas configurações.

Dessa forma podemos cancelar os PRs anteriores e resolver tudo neste!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ivmarcos , para fazer isso, precisamos decidir se serão passadas as mesmas configurações para todos os serviços ou cada um pode receber uma configuração diferente (vide exemplo #190). E se for um para cada provedor, qual será o formato para isso.

O que tenho em mente é fazer algo parecido com:

const config = {
  providersConfig: {
    brasilapi: {
        timeout: 1000,
        proxyURL: '...'
    }
  }
}

Copy link

@ivancorrea ivancorrea Oct 8, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@LorhanSohaky

Exatamente! Cada provider precisa receber configurações específicas, mas acredito que poderia ter uma opção pra definir geral:

const config = {
	providersConfig: {
		//specific providers
		brasilapi: {
			timeout: 1000,
			proxyURL: '...',
			headers: {
				'user-agent': 'especific ua'
			}
		},
		// for all providers
		timeout: 2000,		
		headers: {
			'user-agent': 'cep-promise'
		}
	}
}

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Modifiquei, agora suporta sobrescrever os headers e adicionar timeout

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ivancorrea consegue fazer o review?

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

Expand Down
3 changes: 1 addition & 2 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default [
input,
plugins: [
replace({
'node-fetch': 'unfetch',
'node-fetch': 'unfetch'
})
].concat(defaultPlugins, [
resolve({
Expand All @@ -43,4 +43,3 @@ export default [
}
}
]

18 changes: 10 additions & 8 deletions src/cep-promise.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default function (cepRawValue, configurations = {}) {
.then(cepRawValue => {
configurations.providers = configurations.providers ? configurations.providers : []
validateProviders(configurations.providers)

return cepRawValue
})
.then(removeSpecialCharacters)
Expand All @@ -26,7 +26,7 @@ export default function (cepRawValue, configurations = {}) {
}

function validateProviders (providers) {
let availableProviders = ['brasilapi', 'correios', 'viacep', 'widenet']
const availableProviders = ['brasilapi', 'correios', 'viacep', 'widenet']

if (!Array.isArray(providers)) {
throw new CepPromiseError({
Expand All @@ -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'
}
]
Expand Down Expand Up @@ -107,17 +107,19 @@ function validateInputLength (cepWithLeftPad) {
}

function fetchCepFromServices (cepWithLeftPad, configurations) {
let providersServices = getAvailableServices()
const providersServices = getAvailableServices()

const { providers: providersFromConfigurations, ...configurationsWithoutProviders } = configurations

if (configurations.providers.length === 0) {
if (providersFromConfigurations.length === 0) {
return Promise.any(
Object.values(providersServices).map(provider => provider(cepWithLeftPad))
Object.values(providersServices).map(provider => provider(cepWithLeftPad, configurationsWithoutProviders))
)
}

return Promise.any(
configurations.providers.map(provider => {
return providersServices[provider](cepWithLeftPad)
providersFromConfigurations.map(provider => {
return providersServices[provider](cepWithLeftPad, configurationsWithoutProviders)
})
)
}
Expand Down
7 changes: 4 additions & 3 deletions src/services/brasilapi.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
import fetch from 'node-fetch'
import ServiceError from '../errors/service.js'

export default function fetchBrasilAPIService (cepWithLeftPad) {
export default function fetchBrasilAPIService (cepWithLeftPad, { agent = undefined }) {
const url = `https://brasilapi.com.br/api/cep/v1/${cepWithLeftPad}`
const options = {
method: 'GET',
mode: 'cors',
headers: {
'content-type': 'application/json;charset=utf-8'
}
},
agent
}

return fetch(url, options)
Expand All @@ -23,7 +24,7 @@ function parseResponse (response) {
if (response.ok === false || response.status !== 200) {
throw new Error('CEP não encontrado na base do BrasilAPI.')
}

return response.json()
}

Expand Down
7 changes: 4 additions & 3 deletions src/services/correios.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@
import fetch from 'node-fetch'
import ServiceError from '../errors/service.js'

export default function fetchCorreiosService (cepWithLeftPad, proxyURL = '') {
export default function fetchCorreiosService (cepWithLeftPad, { proxyURL = '', agent = undefined }) {
const url = `${proxyURL}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'
}
},
agent
}

return fetch(url, options)
Expand Down Expand Up @@ -72,7 +73,7 @@ function extractValuesFromSuccessResponse (xmlObject) {
city: xmlObject.cidade,
neighborhood: xmlObject.bairro,
street: xmlObject.end,
service: 'correios',
service: 'correios'
}
}

Expand Down
7 changes: 4 additions & 3 deletions src/services/viacep.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@
import fetch from 'node-fetch'
import ServiceError from '../errors/service.js'

export default function fetchViaCepService (cepWithLeftPad, proxyURL = '') {
export default function fetchViaCepService (cepWithLeftPad, { proxyURL = '', agent = undefined }) {
const url = `${proxyURL}https://viacep.com.br/ws/${cepWithLeftPad}/json/`
const options = {
method: 'GET',
mode: 'cors',
headers: {
'content-type': 'application/json;charset=utf-8',
'user-agent': ''
}
},
agent
}

return fetch(url, options)
Expand Down Expand Up @@ -44,7 +45,7 @@ function extractCepValuesFromResponse (responseObject) {
city: responseObject.localidade,
neighborhood: responseObject.bairro,
street: responseObject.logradouro,
service: 'viacep',
service: 'viacep'
}
}

Expand Down
5 changes: 3 additions & 2 deletions src/services/widenet.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
import fetch from 'node-fetch'
import ServiceError from '../errors/service.js'

export default function fetchWideNetService (cepWithLeftPad, proxyURL = '') {
export default function fetchWideNetService (cepWithLeftPad, { proxyURL = '', agent = undefined }) {
const url = `${proxyURL}https://cep.widenet.host/busca-cep/api/cep/${cepWithLeftPad}.json`
const options = {
method: 'GET',
mode: 'cors',
headers: {
'content-type': 'application/json;charset=utf-8'
}
},
agent
}

return fetch(url, options)
Expand Down
55 changes: 37 additions & 18 deletions test/e2e/cep-promise.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,33 @@ 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'

chai.use(chaiAsPromised)
chai.use(chaiSubset)

let expect = chai.expect
const expect = chai.expect

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 => {
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
})
})
)
})

Expand All @@ -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
})
})
})

Expand Down