{"size": 1755, "ext": "js", "max_stars_repo_path": "src/services/httpService.js", "max_stars_repo_name": "ezeportela/nodexe-services", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/services/httpService.js", "max_issues_repo_name": "ezeportela/nodexe-services", "max_issues_repo_issues_event_min_datetime": "2021-05-11T05:35:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-11T05:35:15.000Z", "max_forks_repo_path": "src/services/httpService.js", "max_forks_repo_name": "ezeportela/nodexe-services", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 1, "max_forks_count": null, "avg_line_length": 20.6470588235, "max_line_length": 72, "alphanum_fraction": 0.5834757835}
const axios = require('axios');
const url = require('url');
const _ = require('lodash');
const https = require('https');
const config = require('config');

class HttpService {
  getName() {
    return '';
  }

  getMethod() {
    return 'get';
  }

  getConnection() {
    return config.get(`services.${this.getName()}.url`);
  }

  getURI(requestData = {}) {
    let uri = url.format(this.getConnection());
    for (const key of Object.keys(requestData)) {
      uri = uri.replace(`:${key}`, requestData[key]);
    }
    return uri;
  }

  async getHeaders(requestData) {
    return null;
  }

  getRequestData(requestData) {
    return requestData;
  }

  getSSL() {
    return {};
  }

  log(name, message) {
    console.log(name, message);
  }

  async request(requestData) {
    try {
      const name = this.getName();
      const method = this.getMethod();
      const url = this.getURI(requestData);
      const headers = await this.getHeaders(requestData);
      const bodyType = this.getMethod() === 'get' ? 'params' : 'data';

      const options = {
        name,
        method,
        url,
        headers,
        [bodyType]: this.getRequestData(requestData),
      };

      this.log('start_call_service', options);

      const ssl = this.getSSL();
      if (!_.isEmpty(ssl)) {
        const httpsAgent = new https.Agent(ssl);
        Object.assign(options, {httpsAgent});
        this.log('service_ssl', 'the ssl has been loaded successfully');
      }

      const response = await axios(options);

      this.log('end_call_service', {
        name,
        response: response.data,
      });

      return response;
    } catch (err) {
      this.log('service_error', err);
      throw err;
    }
  }
}

module.exports = HttpService;
