Skip to content

Commit e34ab73

Browse files
mshlzlucianopf
authored andcommitted
add Correios Alt service provider
1 parent faf125f commit e34ab73

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/services/correios-alt.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
'use strict'
2+
3+
import fetch from 'node-fetch'
4+
import ServiceError from '../errors/service.js'
5+
6+
export default function fetchCorreiosAltAPIService(
7+
cepWithLeftPad,
8+
proxyURL = ''
9+
) {
10+
const url = `${proxyURL}https://buscacepinter.correios.com.br/app/cep/carrega-cep.php?cep=${cepWithLeftPad}`
11+
const options = {
12+
method: 'GET',
13+
mode: 'cors',
14+
headers: {
15+
'content-type': 'application/json;charset=utf-8'
16+
}
17+
}
18+
19+
return fetch(url, options)
20+
.then(parseResponse)
21+
.then(extractCepValuesFromResponse)
22+
.catch(throwApplicationError)
23+
}
24+
25+
async function parseResponse(response) {
26+
response = await response.json()
27+
28+
if (response.erro === true || response.total === 0) {
29+
throw new Error('CEP não encontrado na base dos Correios.')
30+
}
31+
32+
return response
33+
}
34+
35+
function extractCepValuesFromResponse(response) {
36+
const firstCep = response.dados[0]
37+
return {
38+
cep: firstCep.cep,
39+
state: firstCep.uf,
40+
city: firstCep.localidade,
41+
neighborhood: firstCep.bairro,
42+
street: firstCep.logradouroDNEC,
43+
service: 'correios'
44+
}
45+
}
46+
47+
function throwApplicationError(error) {
48+
const serviceError = new ServiceError({
49+
message: error.message,
50+
service: 'correios'
51+
})
52+
53+
if (error.name === 'FetchError') {
54+
serviceError.message = 'Erro ao se conectar com o serviço dos Correios.'
55+
}
56+
57+
throw serviceError
58+
}

src/services/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import Correios from './correios'
2+
import CorreiosAlt from './correios-alt'
23
import ViaCep from './viacep'
34
import WideNet from './widenet'
45
import BrasilAPI from './brasilapi.js'
@@ -16,6 +17,7 @@ export function getAvailableServices () {
1617

1718
return {
1819
correios: Correios,
20+
'correios-alt': CorreiosAlt,
1921
viacep: ViaCep,
2022
widenet: WideNet,
2123
brasilapi: BrasilAPI

0 commit comments

Comments
 (0)