DEV Community

Discussion on: The Bridge Pattern - Design Patterns meet the Frontend

Collapse
 
yaldram profile image
Arsalan Ahmed Yaldram • Edited

Sir thank you so much for this great article : -

Here is how I use services using Composition over Inheritance like so

a. under crud.js I have -

 export const fetchAllResources = state => ({
  fetchAll(config = {}) {
    return API.get(`/${state.resource}`, {
      ...config
    });
  }
});

export const fetchResourceByHierarchyLevel = state => ({
  fetchResourceByHierarchyLevel(hierarchyLevel, config = {}) {
    return API.get(`/${state.resource}/${hierarchyLevel}`, {
      ...config
    });
  }
});

export const fetchHistory = state => ({
  fetchHistory(resourceId, updateValues, config = {}) {
    return API.get(`/${state.resource}/history/${resourceId}`, updateValues, {
      ...config
    });
  }
});

b. Here is my API file like so : -

  import {
  fetchResourceByHierarchyLevel,
  hideResource,
  unHideResource,
  addResource
} from "./crud";

function HighlightsCrud(resource) {
  const state = {
    resource
  };

  return Object.assign(
    state,
    fetchResourceByHierarchyLevel(state),
    addResource(state),
    hideResource(state),
    unHideResource(state)
  );
}

export const highlightsAPI = HighlightsCrud(`highlights`);

What I find after reading your post, your approach is more Object Oriented based suited for TypeScript(which is great) and Type-Safe. I will use your approach next time.

Please share some thoughts, Thanks

Collapse
 
coly010 profile image
Colum Ferry

From ES6 onwards you have access to the class keyword, if you don't want to switch to Typescript just yet :)