Miles Collier
Miles Collier

Reputation: 370

Vue.js best approach to organize API endpoints?

On my components I am having to access my endpoints (API Gateway/Lambda), this is currently requiring me to hardcode this on a per-component level. Obviously not ideal, haha.

Here is an example of what I have now on a Vue component:

async mounted() {
    axios.get('https://XXXXXXX.execute-api.us-east-1.amazonaws.com/{environment}/{endpoint_name}')
      .then(response => {
        this.data = response.data;
      })
  }

Ideally I am trying to find an elegant way of populating these axios.get() sections, so I can have a main reference for the execution id and environment (dev/qa/prod/etc).

I am new to Vue.js, so I am struggling to find the ideal approach. Currently my thought would be to create string that pulls from main.js then adds onto the .get url. Such as .get(LAMBDA_URL + 'test'), ideas?

Upvotes: 2

Views: 2844

Answers (1)

Sumurai8
Sumurai8

Reputation: 20737

First of all, you can abstract away all api calls to their own file, somewhere in an api folder. You can then make your own get, post, put and delete methods that perform some basic boilerplate stuff like prepending the lambda url and parsing common things such as the status code.

You can go further by only calling these api endpoints in your vuex store if you have one. The nice part of that is that your components are no longer concerned where they get the data from. The implementation of getting the data is all in some fetch action somewhere in your store. Your components will use a getter to show things.

// api/index.js
import { apiUrl } from '@/config';

function apiRequest(method, url, data, whatever) {
  return axios({
    method,
    data,
    url: `${apiUrl}/${url}`
    // etc
  });
}

export function get(url, data, whatever) {
  return apiRequest('get', url, data, whatever);
}

// etc
// Component
<template>
  <div>
    {{ data }}
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  name: 'my-component',
  computed: {
    ...mapGetters({
      data: 'animals/birds'
    })
  },

  mounted () {
    this.$store.dispatch('animals/fetchBirds');
  }
}
</script>

Upvotes: 5

Related Questions