Dependency Installation
npm install axios querystring
Client Configuration
Create a network directory and add client.js to handle the base setup and interceptors.
import axios from 'axios';
import { stringify } from 'querystring';
import { appRouter } from '@/routing';
const API_GATEWAY = process.env.VUE_APP_API_URL || '/gateway';
const httpInstance = axios.create({
baseURL: API_GATEWAY,
timeout: 25000
});
httpInstance.interceptors.request.use((req) => {
const authToken = localStorage.getItem('auth_token');
if (authToken) {
req.headers.Authorization = `Bearer ${authToken}`;
}
return req;
}, (err) => Promise.reject(err));
httpInstance.interceptors.response.use((res) => res, (err) => {
if (err.response && err.response.status === 401) {
window.alert('Session invalid. Please authenticate again.');
localStorage.removeItem('auth_token');
appRouter.push('/auth');
}
return Promise.reject(err);
});
export const fetchQuery = (path, params = {}) => httpInstance.get(`${path}?${stringify(params)}`);
export const submitPayload = (path, payload = {}) => httpInstance.post(path, stringify(payload));
export const submitJson = (path, payload = {}) => httpInstance.post(path, payload, {
headers: { 'Content-Type': 'application/json' }
});
export const modifyJson = (path, payload = {}) => httpInstance.put(path, payload, {
headers: { 'Content-Type': 'application/json' }
});
export const removeItem = (path, payload = {}) => httpInstance.delete(path, { data: payload });
export const uploadMultipart = (path, payload = {}) => {
const multipartData = new FormData();
Object.keys(payload).forEach(key => multipartData.append(key, payload[key]));
return httpInstance.post(path, multipartData, {
headers: { 'Content-Type': 'multipart/form-data' }
});
};
export const fetchBinary = (path, params) => httpInstance.get(`${path}?${stringify(params)}`, {
responseType: 'blob'
});
export const submitBinary = (path, payload) => httpInstance.post(path, stringify(payload), {
responseType: 'blob'
});
Endpoint Definitions
Inside the network folder, create endpoints.js to map specific routes.
import { fetchQuery, submitJson } from './client';
export default {
fetchSampleData: (criteria) => fetchQuery('/sample-resource', criteria),
createSampleRecord: (data) => submitJson('/sample-resource', data)
};
Module Aggregation
Create network/index.js to unify the exports.
import endpoints from './endpoints';
export default endpoints;
Global Registration
Attach the service to the Vue prototype within main.js.
import Vue from 'vue';
import networkLayer from './network';
Vue.prototype.$network = networkLayer;
Component Execution
this.$network.fetchSampleData({ id: 123 }).then(response => {
console.log(response.data);
});