File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 11import Correios from './correios'
2+ import CorreiosAlt from './correios-alt'
23import ViaCep from './viacep'
34import WideNet from './widenet'
45import 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
You can’t perform that action at this time.
0 commit comments