Search This Blog

2023/08/30

adapter design pattern in javascript

 // External API 1 (Adaptee)

class WeatherAPI1 {
getWeatherData() {
// API-specific implementation and response format
return {
temperature: 25,
humidity: 70,
windSpeed: 12,
};
}
}

// External API 2 (Adaptee)
class WeatherAPI2 {
fetchData() {
// API-specific implementation and response format
return {
temp: 30,
humid: 60,
wind: 8,
};
}
}

// Unified Weather API (Target Interface)
class WeatherAPI {
constructor(adapter) {
this.adapter = adapter;
}

getWeather() {
const data = this.adapter.fetchData();
// Common data format for the application
return {
temperature: data.temp || data.temperature,
humidity: data.humid || data.humidity,
windSpeed: data.wind || data.windSpeed,
};
}
}

// Adapters for the external APIs
class API1Adapter {
constructor(api) {
this.api = api;
}

fetchData() {
const data = this.api.getWeatherData();
return {
temperature: data.temperature,
humidity: data.humidity,
windSpeed: data.windSpeed,
};
}
}

class API2Adapter {
constructor(api) {
this.api = api;
}

fetchData() {
const data = this.api.fetchData();
return {
temperature: data.temp,
humidity: data.humid,
windSpeed: data.wind,
};
}
}

// Usage
const api1 = new WeatherAPI1();
const api2 = new WeatherAPI2();

const api1Adapter = new API1Adapter(api1);
const api2Adapter = new API2Adapter(api2);

const weatherAPI = new WeatherAPI(api1Adapter);
console.log(weatherAPI.getWeather()); // Outputs weather data from API 1

weatherAPI.adapter = api2Adapter;
console.log(weatherAPI.getWeather()); // Outputs weather data from API 2

No comments:

Post a Comment