Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
1.3 kB
7
Indexable
Never
const axios = require('axios');
const readline = require('readline-sync');
const fs = require('fs');
const path = require('path');


const END_POINT_URL = 'https://viacep.com.br/ws/';
const END_POINT_DATA_FORMAT = 'json';

const SAVE_PATH = path.resolve('src/data', 'addresses.json');

const cleanCEP = cep => cep.trim().replace(' ', '').replace('-', '');

function checkFileSize() {
  const stats = fs.statSync(SAVE_PATH);
  const { size } = stats;
  if (size > 0) {
    return 1;
  } else {
    return 0;
  }
}

const fetchAPI = async () => {
  try {
    const getCEP = readline.question('Digite o CEP: ');
    const {data: address} = await axios.get(`${END_POINT_URL}${cleanCEP(getCEP)}/${END_POINT_DATA_FORMAT}`);

    if (checkFileSize() === 0 ) {
      const newAddress = new Array();
      newAddress.push(address);
      fs.writeFileSync(SAVE_PATH, JSON.stringify(newAddress, null, 4));
      console.log('File initialized');
      console.log(`Address stored for ZIP ${cleanCEP(getCEP)}`);
    } else {
      const addresses = JSON.parse(fs.readFileSync(SAVE_PATH, 'utf-8'));
      addresses.push(address);
      fs.writeFileSync(SAVE_PATH, JSON.stringify(addresses, null, 4));
      console.log(`Address stored for ZIP ${cleanCEP(getCEP)}`);
    }
  } catch (error) {
    console.log('Invalid CEP');
  }
}

fetchAPI();

Leave a Comment