Nuxt.js - The best place for API calls

谁说我不能喝 提交于 2020-12-31 10:55:34

问题


I'm new to Vue.js Nuxt and all front-end stuff.

I have a question about API calls. I'm not sure what is the right way, the best practice here.

I have a store. In that store, I have actions that are calling my API and sets state eg.

async fetchArticle({ state, commit }, uuid) {
    const response = await this.$axios.get(`articles/${uuid}/`)
    commit('SET_ARTICLE', response.data)
},

And that is fine it is working for one component.

But what if I want to just fetch the article and not changing the state.

To be DRY first thing that comes to my mind is to create the service layer that is fetching the data and is used where it is needed.

Is it the right approach? Where can I find some real-world examples that I can take inspiration from?


回答1:


Using the repository pattern to abstract your API is definitely a good idea! Whether you use the @nuxtjs/axios module or the @nuxt/http module, you can pass either instance to your repository class/function. Below a real world example of an abstracted "repository.js" file.

export default $axios => resource => ({
  index() {
    return $axios.$get(`/${resource}`)
  },

  create(payload) {
    return $axios.$post(`/${resource}`, payload)
  },

  show(id) {
    return $axios.$get(`/${resource}/${id}`)
  },


  update(payload, id) {
    return $axios.$put(`/${resource}/${id}`, payload)
  },

  delete(id) {
    return $axios.$delete(`/${resource}/${id}`)
  }

})

You can then create a plugin to initialize all different kinds of repositories for your endpoints:

import createRepository from '~/path/to/repository.js'

export default (ctx, inject) => {
  const repositoryWithAxios = createRepository(ctx.$axios)

  const repositories = {
    posts: repositoryWithAxios('posts'),
    users: repositoryWithAxios('users')
    //...
  }

  inject('repositories', repositories)
}

Further read: Organize and decouple your API calls in Nuxt.js




回答2:


I will an example of a service layer implementation for my portfolio to create my dashboard that shows some statics about my github and stackoverflow profiles, to do this i created a folder called services inside the project root :

pages
services
  |_AxiosConfig.js
  |_GitHubService.js
  |_StackoverflowService.js
   ...

in the AxiosConfig.js file i put i created an axios instance with its configuration :

import axios from 'axios';

const clientAPI = url =>
  axios.create({
    baseURL: url,
    withCredentials: false,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
   
  });

export default clientAPI;

then in my GitHubService.js i imported that axios instance called clientAPI which i used to my requests :

import clientAPI from './AxiosConfig';

const baseURL = 'https://api.github.com';
export default {
  getUser(name) {
    return clientAPI(baseURL).get('/users/' + name);
  },
  getRepos(name){
    return clientAPI(baseURL).get('/users/' + name+'/repos');

  },
  getEvents(name,page){

    return clientAPI(baseURL).get('/users/' + name+'/events?per_page=100&page='+page);

  },
  getLastYearCommits(name,repo){

    return clientAPI(baseURL).get('/repos/' + name+'/'+repo+'/stats/commit_activity');

  }

};

then in my page i used asyncData hook to fetch my data :

import GitHubService from '../../services/GitHubService'

export default {
 ...
  async asyncData({ error }) {
    try {
      const { data } = await GitHubService.getUser("boussadjra");
      const resRepos = await GitHubService.getRepos("boussadjra");
      return {
        user: data,
        repos: resRepos.data
      };
    } catch (e) {
      error({
        statusCode: 503,
        message: "We cannot find the user"
      });
    }
  }



回答3:


In Nuxt, if you want to just get the data without keeping it in your store, you could use the asyncData function, which asynchronously loads data (from API calls and the like) and pushes it into the component's data object before rendering.



来源:https://stackoverflow.com/questions/63693060/nuxt-js-the-best-place-for-api-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!