A simple explanation of Adapter Pattern with Vue.js

a-simple-explanation-of-adapter-pattern-with-vue.js

Hi there.

Today I will share how I understood the Adapter Pattern using Vue.js. In short, the Adapter Pattern in Vue.js is used to “adapt” the interface of a component, method, or service so that it can be used in a compatible way with other parts of the code that expect a different interface.

This pattern is useful for integrating third-party components, APIs, or libraries that are not directly compatible with your Vue.js application, allowing for smoother, more flexible integration.

Here is an example:

1- I have a Home.vue file that will do a request to a random API (restcountries):


Here is the return of the API request:
Return of API

So, let’s imagine that we only need three variables from this response, formatted in a specific way:

interface Country {
  countryName: string
  countryCapital: string
  countryPopulation: number
}

2- I will create another file named adapters.ts and define a function to transform the current format into the one expected by the Country interface:

interface Country {
  countryName: string
  countryCapital: string
  countryPopulation: number
}

// Function that receives the API response and adapts it to an array of Country objects
export function getCountryAdapter(apiResponse: any): Country[] {
  // Check if is an array
  if (!Array.isArray(apiResponse)) {
    throw new Error('The API response is not a Array of countries.')
  }

  // Maps each country in the response to the Country object format
  const countries: Country[] = apiResponse.map((country: any) => ({
    countryName: country.name.common,
    countryCapital: country.capital[0],
    countryPopulation: country.population,
  }))

  return countries
}

3- Now, let’s call the adapter in the Home.vue file:


4- The final result is the response adapted to the interface 😊:

Adapted response

If you have any suggestions, please let me know. Thank you so much for reading!

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
implementing-infinite-scroll-in-react-apps

Implementing Infinite scroll in React apps

Next Post
culture-of-quality-takes-center-stage-in-latest-boeing-news

Culture of Quality Takes Center Stage in Latest Boeing News

Related Posts