Created
December 17, 2017 20:11
-
-
Save suissa/e71f5dd66b8a87864896c5ec781ee654 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require( 'express' ) | |
const axios = require( 'axios' ) | |
const app = express() | |
const isCepValid = ( cep ) => | |
( cep.length < 8 || cep.length > 9 ) | |
? new Error( 'Cep inválido' ) | |
: true | |
const sanitizeCEP = ( cep ) => cep.replace( /\D/g, '' ) | |
const getCEP = ( req, res ) => { | |
const codeFormated = sanitizeCEP( req.query.code ) | |
if ( isCepValid( codeFormated ) instanceof Error ) { | |
res.status( 400 ) | |
return res.send( 'Cep inválido' ) | |
} | |
axios.get( 'https://viacep.com.br/ws/' + codeFormated + '/json' ) | |
.then( function ( response ) { | |
console.log( response ) | |
res.json( response.data ) | |
} ) | |
.catch( function ( error ) { | |
console.log( error ) | |
} ) | |
} | |
app.get( '/cep', getCEP ) | |
app.listen( 9000 ) | |
console.log( 'Server started! At http://localhost:9000' ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment