Skip to content

Instantly share code, notes, and snippets.

@cBevilaqua
Created November 22, 2018 11:52
Show Gist options
  • Select an option

  • Save cBevilaqua/b8b7bd542a7cc5d44cba5a1a498c876f to your computer and use it in GitHub Desktop.

Select an option

Save cBevilaqua/b8b7bd542a7cc5d44cba5a1a498c876f to your computer and use it in GitHub Desktop.

Revisions

  1. cBevilaqua created this gist Nov 22, 2018.
    48 changes: 48 additions & 0 deletions api-client.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    import Vue from 'vue'

    export default class ApiClient {
    static callAPI (method, url, data) {
    const options = {
    method: method,
    url: `${process.env.VUE_APP_API_URL}/${url}`,
    headers: {
    'Content-Type': 'application/json'
    }
    }

    // add the block below, if you want to add authentication
    // get the local user token to authenticated requests
    let localUser = localStorage.getItem('mylocaluserwithtoken')

    if (localUser) {
    localUser = JSON.parse(localUser)
    if (localUser.token) {
    options.headers['Authorization'] = `Bearer ${localUser.token}`
    }
    }

    if (data) {
    options.body = data
    }

    return new Promise((resolve, reject) => {
    Vue.http(options).then(resp => {
    resolve(resp.body)
    }).catch(err => {
    reject(err)
    })
    });
    }
    static apiGet (url) {
    return this.callAPI('GET', url)
    }
    static apiPost (url, data) {
    return this.callAPI('POST', url, data)
    }
    static apiPut (url, data) {
    return this.callAPI('PUT', url, data)
    }
    static apiDelete (url) {
    return this.callAPI('DELETE', url)
    }
    }