1
\$\begingroup\$

I was experimenting with some code to fetch the current weather data as well as getting the hourly forecast. I could have done written some functions to get the thing done but I want to learn object composition to learn more about it. Below is my code:

import axios from 'axios'

const weatherService = {
  fetch: async endpoint => await axios.get(endpoint)
}

const weatherApi = {
  currentWeather: async city => {
    try {
      const { data: { data } } = await this.service.fetch(this.config.endpoints.curr + city)
      return this.handleCurrentData(data)
    } catch(e) {
      this.handleError(e)
    }
  },
  hourlyForecast: async city => {
    try {
      const { data: { data } } = await this.service.fetch(this.config.endpoints.hour + city)
      return this.handleHourlyData(data)
    } catch(e) {
      this.handleError(e)
    }
  }
};

const defaultConfig = {
  endpoints: {
    curr: `http://api.openweathermap.org/data/2.5/weather?q=`,
    hour: `http://api.openweathermap.org/data/2.5/forecast?q=`
  }
};

const api = (api, config, service) => {
  return {
    Object.create(weatherApi),
    Object.create(service),
    Object.create(config),
    ...obj
  }
};

// dependency injection for testing
module.exports = (obj, config=defaultConfig, service=weatherService) => {
  return api(obj, config, service)
};


// Usage
const weatherAPI = require('api')({
  handleCurrentData: (data) => console.log(data),
  handleHourlyData: (data) => console.log(data)
});

weatherAPI.currentWeather('London');
weatherAPI.hourlyWeather('London');

I would like to know if my approach is correct? also, what can I do to improve the readability, flexibility of the code?

\$\endgroup\$
  • \$\begingroup\$ You're using ES6 arrow functions, so why not use ES6 classes? \$\endgroup\$ – I wrestled a bear once. Jul 26 '17 at 13:36
  • 1
    \$\begingroup\$ Does this code even work? I spot a few things that indicate it doesn't. \$\endgroup\$ – Joseph Jul 26 '17 at 15:23
  • \$\begingroup\$ Has this code changed since last July? If so, are you able to update it? Like Joesph commented: it appears not to work.. \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ Jun 27 '18 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.