I am still trying to get in my head the object fundamentals in javascript which seems to be quite different than classical paradigm. I have written a toy example to fetch weather data, the code is below:
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)
return this.handleCurrentData(data)
} catch(e) {
this.handleError(e)
}
},
hourlyForecast: async city => {
try {
const { data: { data } } = await this.service.fetch(this.config.endpoints.hour)
return this.handleHourlyData(data)
} catch(e) {
this.handleError(e)
}
}
};
const defaultConfig = {
key: process.env.API_KEY,
endpoints: {
curr: `/current/geosearch?key=${this.key}`,
hour: `/forecast/3hourly/geosearch?key=${this.key}`
}
};
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 I am going in the correct direction? If not what are improvement in thinking process as well as in code needed?
PS: I know I could have written the above api easily by exporting functions but this is an attempt to learn object composition.