Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Configurações da biblioteca e adição de keep-alive #191

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

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 [
}
}
]

29 changes: 22 additions & 7 deletions src/cep-promise.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({
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,32 @@ function validateInputLength (cepWithLeftPad) {
}

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

if (configurations.providers.length === 0) {
const { providers: providersFromConfigurations, ...configurationsWithoutProviders } = configurations
lucianopf marked this conversation as resolved.
Show resolved Hide resolved

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] })
})
)
}
Expand Down
8 changes: 5 additions & 3 deletions src/services/brasilapi.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
12 changes: 7 additions & 5 deletions src/services/correios.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -73,7 +75,7 @@ function extractValuesFromSuccessResponse (xmlObject) {
city: xmlObject.cidade,
neighborhood: xmlObject.bairro,
street: xmlObject.end,
service: 'correios',
service: 'correios'
}
}

Expand Down
10 changes: 6 additions & 4 deletions src/services/viacep.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down Expand Up @@ -48,7 +50,7 @@ function extractCepValuesFromResponse (responseObject) {
city: responseObject.localidade,
neighborhood: responseObject.bairro,
street: responseObject.logradouro,
service: 'viacep',
service: 'viacep'
}
}

Expand Down
8 changes: 5 additions & 3 deletions src/services/widenet.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
53 changes: 36 additions & 17 deletions test/e2e/cep-promise.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ 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(() => {
Expand All @@ -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
})
})
)
})

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