Skip to content

Commit c9a3b52

Browse files
feature: implements BrasilAPI service
1 parent b6e367a commit c9a3b52

12 files changed

+397
-23
lines changed

dist/cep-promise-browser.js

Lines changed: 52 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,50 @@
540540
throw serviceError;
541541
}
542542

543+
function fetchBrasilAPIService(cepWithLeftPad) {
544+
var url = "https://brasilapi.com.br/api/cep/v1/".concat(cepWithLeftPad);
545+
var options = {
546+
method: 'GET',
547+
mode: 'cors',
548+
headers: {
549+
'content-type': 'application/json;charset=utf-8'
550+
}
551+
};
552+
return fetch(url, options).then(parseResponse).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3);
553+
}
554+
555+
function parseResponse(response) {
556+
if (response.ok === false || response.status !== 200) {
557+
throw new Error('CEP não encontrado na base do BrasilAPI.');
558+
}
559+
560+
return response.json();
561+
}
562+
563+
function extractCepValuesFromResponse$2(response) {
564+
return {
565+
cep: response.cep,
566+
state: response.state,
567+
city: response.city,
568+
neighborhood: response.neighborhood,
569+
street: response.street,
570+
service: 'brasilapi'
571+
};
572+
}
573+
574+
function throwApplicationError$3(error) {
575+
var serviceError = new ServiceError({
576+
message: error.message,
577+
service: 'brasilapi'
578+
});
579+
580+
if (error.name === 'FetchError') {
581+
serviceError.message = 'Erro ao se conectar com o serviço BrasilAPI.';
582+
}
583+
584+
throw serviceError;
585+
}
586+
543587
var PROXY_URL = 'https://proxier.now.sh/api?url=';
544588

545589
/* istanbul ignore next */
@@ -559,6 +603,7 @@
559603
var CorreiosService = isBrowser() ? injectProxy(fetchCorreiosService) : fetchCorreiosService;
560604
var ViaCepService = fetchViaCepService;
561605
var WideNetService = fetchWideNetService;
606+
var BrasilAPIService = fetchBrasilAPIService;
562607

563608
var reverse = function reverse(promise) {
564609
return new Promise(function (resolve, reject) {
@@ -581,11 +626,11 @@
581626
return cepRawValue;
582627
}).then(removeSpecialCharacters).then(validateInputLength).then(leftPadWithZeros).then(function (cepWithLeftPad) {
583628
return fetchCepFromServices(cepWithLeftPad, configurations);
584-
})["catch"](handleServicesError)["catch"](throwApplicationError$3);
629+
})["catch"](handleServicesError)["catch"](throwApplicationError$4);
585630
}
586631

587632
function validateProviders(providers) {
588-
var availableProviders = ['correios', 'viacep', 'widenet'];
633+
var availableProviders = ['brasilapi', 'correios', 'viacep', 'widenet'];
589634

590635
if (!Array.isArray(providers)) {
591636
throw new CepPromiseError({
@@ -610,7 +655,7 @@
610655
message: 'Erro ao inicializar a instância do CepPromise.',
611656
type: 'validation_error',
612657
errors: [{
613-
message: "O provider \"".concat(provider, "\" \xE9 inv\xE1lido. Os providers dispon\xEDveis s\xE3o: ").concat(availableProviders.join(", "), "."),
658+
message: "O provider \"".concat(provider, "\" \xE9 inv\xE1lido. Os providers dispon\xEDveis s\xE3o: [\"").concat(availableProviders.join('", "'), "\"]."),
614659
service: 'providers_validation'
615660
}]
616661
});
@@ -667,9 +712,10 @@
667712

668713
function fetchCepFromServices(cepWithLeftPad, configurations) {
669714
var providersServices = {
670-
correios: CorreiosService,
715+
brasilapi: BrasilAPIService,
716+
viacep: ViaCepService,
671717
widenet: WideNetService,
672-
viacep: ViaCepService
718+
correios: CorreiosService
673719
};
674720

675721
if (configurations.providers.length === 0) {
@@ -695,7 +741,7 @@
695741
throw aggregatedErrors;
696742
}
697743

698-
function throwApplicationError$3(_ref) {
744+
function throwApplicationError$4(_ref) {
699745
var message = _ref.message,
700746
type = _ref.type,
701747
errors = _ref.errors;

dist/cep-promise-browser.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

dist/cep-promise.js

Lines changed: 52 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,50 @@
491491
throw serviceError;
492492
}
493493

494+
function fetchBrasilAPIService(cepWithLeftPad) {
495+
var url = "https://brasilapi.com.br/api/cep/v1/".concat(cepWithLeftPad);
496+
var options = {
497+
method: 'GET',
498+
mode: 'cors',
499+
headers: {
500+
'content-type': 'application/json;charset=utf-8'
501+
}
502+
};
503+
return fetch(url, options).then(parseResponse).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3);
504+
}
505+
506+
function parseResponse(response) {
507+
if (response.ok === false || response.status !== 200) {
508+
throw new Error('CEP não encontrado na base do BrasilAPI.');
509+
}
510+
511+
return response.json();
512+
}
513+
514+
function extractCepValuesFromResponse$2(response) {
515+
return {
516+
cep: response.cep,
517+
state: response.state,
518+
city: response.city,
519+
neighborhood: response.neighborhood,
520+
street: response.street,
521+
service: 'brasilapi'
522+
};
523+
}
524+
525+
function throwApplicationError$3(error) {
526+
var serviceError = new ServiceError({
527+
message: error.message,
528+
service: 'brasilapi'
529+
});
530+
531+
if (error.name === 'FetchError') {
532+
serviceError.message = 'Erro ao se conectar com o serviço BrasilAPI.';
533+
}
534+
535+
throw serviceError;
536+
}
537+
494538
var PROXY_URL = 'https://proxier.now.sh/api?url=';
495539

496540
/* istanbul ignore next */
@@ -510,6 +554,7 @@
510554
var CorreiosService = isBrowser() ? injectProxy(fetchCorreiosService) : fetchCorreiosService;
511555
var ViaCepService = fetchViaCepService;
512556
var WideNetService = fetchWideNetService;
557+
var BrasilAPIService = fetchBrasilAPIService;
513558

514559
var reverse = function reverse(promise) {
515560
return new Promise(function (resolve, reject) {
@@ -532,11 +577,11 @@
532577
return cepRawValue;
533578
}).then(removeSpecialCharacters).then(validateInputLength).then(leftPadWithZeros).then(function (cepWithLeftPad) {
534579
return fetchCepFromServices(cepWithLeftPad, configurations);
535-
})["catch"](handleServicesError)["catch"](throwApplicationError$3);
580+
})["catch"](handleServicesError)["catch"](throwApplicationError$4);
536581
}
537582

538583
function validateProviders(providers) {
539-
var availableProviders = ['correios', 'viacep', 'widenet'];
584+
var availableProviders = ['brasilapi', 'correios', 'viacep', 'widenet'];
540585

541586
if (!Array.isArray(providers)) {
542587
throw new CepPromiseError({
@@ -561,7 +606,7 @@
561606
message: 'Erro ao inicializar a instância do CepPromise.',
562607
type: 'validation_error',
563608
errors: [{
564-
message: "O provider \"".concat(provider, "\" \xE9 inv\xE1lido. Os providers dispon\xEDveis s\xE3o: ").concat(availableProviders.join(", "), "."),
609+
message: "O provider \"".concat(provider, "\" \xE9 inv\xE1lido. Os providers dispon\xEDveis s\xE3o: [\"").concat(availableProviders.join('", "'), "\"]."),
565610
service: 'providers_validation'
566611
}]
567612
});
@@ -618,9 +663,10 @@
618663

619664
function fetchCepFromServices(cepWithLeftPad, configurations) {
620665
var providersServices = {
621-
correios: CorreiosService,
666+
brasilapi: BrasilAPIService,
667+
viacep: ViaCepService,
622668
widenet: WideNetService,
623-
viacep: ViaCepService
669+
correios: CorreiosService
624670
};
625671

626672
if (configurations.providers.length === 0) {
@@ -646,7 +692,7 @@
646692
throw aggregatedErrors;
647693
}
648694

649-
function throwApplicationError$3(_ref) {
695+
function throwApplicationError$4(_ref) {
650696
var message = _ref.message,
651697
type = _ref.type,
652698
errors = _ref.errors;

dist/cep-promise.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/cep-promise.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
CorreiosService,
66
ViaCepService,
77
WideNetService,
8+
BrasilAPIService
89
} from './services/index.js'
910
import Promise from './utils/promise-any.js'
1011

@@ -30,7 +31,7 @@ export default function (cepRawValue, configurations = {}) {
3031
}
3132

3233
function validateProviders (providers) {
33-
let availableProviders = ['correios', 'viacep', 'widenet']
34+
let availableProviders = ['brasilapi', 'correios', 'viacep', 'widenet']
3435

3536
if (!Array.isArray(providers)) {
3637
throw new CepPromiseError({
@@ -54,7 +55,7 @@ function validateProviders (providers) {
5455
errors: [
5556
{
5657
message:
57-
`O provider "${provider}" é inválido. Os providers disponíveis são: ${availableProviders.join(", ")}.`,
58+
`O provider "${provider}" é inválido. Os providers disponíveis são: ["${availableProviders.join('", "')}"].`,
5859
service: 'providers_validation'
5960
}
6061
]
@@ -112,9 +113,10 @@ function validateInputLength (cepWithLeftPad) {
112113

113114
function fetchCepFromServices (cepWithLeftPad, configurations) {
114115
const providersServices = {
115-
correios: CorreiosService,
116-
widenet: WideNetService,
116+
brasilapi: BrasilAPIService,
117117
viacep: ViaCepService,
118+
widenet: WideNetService,
119+
correios: CorreiosService
118120
}
119121

120122
if (configurations.providers.length === 0) {

src/services/brasilapi.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'use strict'
2+
3+
import fetch from 'node-fetch'
4+
import ServiceError from '../errors/service.js'
5+
6+
export default function fetchBrasilAPIService (cepWithLeftPad) {
7+
const url = `https://brasilapi.com.br/api/cep/v1/${cepWithLeftPad}`
8+
const options = {
9+
method: 'GET',
10+
mode: 'cors',
11+
headers: {
12+
'content-type': 'application/json;charset=utf-8'
13+
}
14+
}
15+
16+
return fetch(url, options)
17+
.then(parseResponse)
18+
.then(extractCepValuesFromResponse)
19+
.catch(throwApplicationError)
20+
}
21+
22+
function parseResponse (response) {
23+
if (response.ok === false || response.status !== 200) {
24+
throw new Error('CEP não encontrado na base do BrasilAPI.')
25+
}
26+
27+
return response.json()
28+
}
29+
30+
function extractCepValuesFromResponse (response) {
31+
return {
32+
cep: response.cep,
33+
state: response.state,
34+
city: response.city,
35+
neighborhood: response.neighborhood,
36+
street: response.street,
37+
service: 'brasilapi'
38+
}
39+
}
40+
41+
function throwApplicationError (error) {
42+
const serviceError = new ServiceError({
43+
message: error.message,
44+
service: 'brasilapi'
45+
})
46+
47+
if (error.name === 'FetchError') {
48+
serviceError.message = 'Erro ao se conectar com o serviço BrasilAPI.'
49+
}
50+
51+
throw serviceError
52+
}

src/services/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import Correios from './correios'
22
import ViaCep from './viacep'
33
import WideNet from './widenet'
4+
import BrasilAPI from './brasilapi.js'
45
import { PROXY_URL } from '../utils/consts'
56

67
/* istanbul ignore next */
@@ -16,3 +17,4 @@ function injectProxy (Service) {
1617
export const CorreiosService = isBrowser() ? injectProxy(Correios) : Correios
1718
export const ViaCepService = ViaCep
1819
export const WideNetService = WideNet
20+
export const BrasilAPIService = BrasilAPI

test/e2e/cep-promise.spec.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import chai from 'chai'
44
import chaiAsPromised from 'chai-as-promised'
55
import chaiSubset from 'chai-subset'
6+
import nock from 'nock'
67

78
import cep from '../../src/cep-promise.js'
89
import CepPromiseError from '../../src/errors/cep-promise.js'
@@ -12,17 +13,22 @@ chai.use(chaiSubset)
1213

1314
let expect = chai.expect
1415

15-
describe('cep-promise (E2E)', () => {
16+
describe('[e2e] cep-promise', () => {
17+
before(() => {
18+
nock.enableNetConnect()
19+
})
20+
1621
describe('when invoked with a valid "05010000" string', () => {
1722
it('should fulfill with correct address', () => cep('05010000')
18-
.then(address => expect(address).to.deep.equal({
23+
.then(address => {
24+
expect(address).to.deep.equal({
1925
cep: '05010000',
2026
state: 'SP',
2127
city: 'São Paulo',
2228
neighborhood: 'Perdizes',
2329
street: 'Rua Caiubi',
2430
service: address.service
25-
}))
31+
})})
2632
)
2733
})
2834

@@ -62,6 +68,11 @@ describe('cep-promise (E2E)', () => {
6268
{
6369
message: 'CEP não encontrado na base do WideNet.',
6470
service: 'widenet'
71+
},
72+
{
73+
name: 'ServiceError',
74+
message: 'CEP não encontrado na base do BrasilAPI.',
75+
service: 'brasilapi'
6576
}
6677
]
6778
})

0 commit comments

Comments
 (0)