vendredi 24 juillet 2020

Is this strategy pattern

To move from one http client to another (same concept can be applied to log libs, db's) I implemented this solution but I am not sure if it's a pattern in OOP world. After looking at some it kinda looks like strategy pattern or repository pattern. But what I understood from repository pattern it is only restricted to data access functionality. However same concept can be applied logging libs, http clients or email client etc.

Here is my implementation of something that I don't know the name: ( =D )

const fetch = require('node-fetch');
const axios = require('axios');
class MyHttpAxios {
  constructor(axios) {
    this.axios = axios;
  }

  async get(url) {
    const response = await this.axios.get(url);
    return response.data;
  }
}

class MyHttpFetch {
  constructor(fetch) {
    this.fetch = fetch;
  }
  async get(url) {
    const response = await this.fetch(url);
    return response.json();
  }
}

const httpClients = {
  axios: new MyHttpAxios(axios),
  fetch: new MyHttpFetch(fetch),
};

const client = httpClients['axios'];
client
  .get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response)
  .then(json => console.log(json));

Aucun commentaire:

Enregistrer un commentaire