Introduce a pattern to call APIs in Vuejs, Reactjs, AngularJs

Tram Ho

In this article I will introduce you a very nice pattern to call API in front-end framwork, which is RepositoryFactory .

Why you should use the RepositoryFactory pattern

We often use repository pattern to get data to separate the data collection and process logic. On the other hand, we often use factory pattern to mock repository and handle logic. How many times have you seen axios initialized over and over again in components?

Each time you are wondering:

  • How to reuse on this component as well as in other projects?
  • What if the endpoints are changed?
  • How to refactor or put into Vuex state?
  • What if there are four resources, not one?
  • How do you write unit tests with components that call all APIs?

Are you willing to edit 30 or more files?

Solution

In this case, to simplify the code and be able to define several different types of resources, I will use POJO (Plain Old JavaScript Objects). You can of course use Class if you want.

Now let’s start to define the axios.

I will name the file Repository.js because it is responsible for connecting to the resources.

Next we will define the Entity for each project.

For example, you have a blog. Then we will have 1 Entity is posts. And now we will define all CRUD operations (Create Update Delete).

And then postsRepository.js will become as follows:

Next we will go to create Factory.

Looking at above we see creating Repository from Factory becomes very simple right?

Moreover here we can easily create mock repository (suitable for each environment, such as develop, staging, production) or add some logic to the above get function is all gone.

Here is how to apply it to the component: Looking at we see it simple is not it? Because the logic part has been separated somewhere else, using another endpoint like GraphSQL is possible.

Conclude

As I see it, this pattern has some advantages:

  • Can easily test a certain code in a simple way
  • Component code looks better
  • Can be easily extended
  • Can ensure DRY (Donot repeat your self)

References

https://medium.com/canariasjs/vue-api-calls-in-a-smart-way-8d521812c322

Share the news now

Source : Viblo