我仍然试图在我的脑海中了解 javascript 中的对象基础,这似乎与经典范式完全不同。我写了一个玩具示例来获取天气数据,代码如下:
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');
我想知道我是否朝着正确的方向前进?如果不是,在思维过程和代码方面需要什么改进?
PS:我知道我可以通过导出函数轻松编写上述 api,但这是学习对象组合的尝试。