service.js 2.82 KB
// Import Axios HTTP Library
import axios from 'axios';

// Public class exported globally
class LemaApi {
    constructor() {
        this.helloWorldMethodUrl = "helloworld/hello";
        this.productOptionsUrl = "helloworld/GetProductOptions"; 
        this.jobsOptionsUrl = "helloworld/GetJobsOptions"; 
        
        // Axios singleton instance 
        this._axios = axios.create({
            baseURL: 'http://localhost:3001/api/',
            timeout: 10000, 
            headers: {
                'X-Custom-Header': 'foobar',
                'Content-Type': 'application/json' // default                
            }
        });
    }

    // Method 1
    getHelloWorld(callback) {
        this._axios.get(this.helloWorldMethodUrl)
        .then(function (response) {
            callback(response.data);
        })
        .catch(function (error) {
            console.log(error);
        });
    };


    // Lista dei prodotti
    getProductOptions() {
        return  this._axios.get(this.productOptionsUrl)
        .then(function (response) {
            return {options: response.data}            
        })
        .catch(function (error) {
            console.log(error);
        });
    };

    // Lista dei settori merceologici
    getJobsOptions() {
        return this._axios.get(this.jobsOptionsUrl)
            .then(function (response) {
                console.log(response.data);
                return { options: response.data }
            })
            .catch(function (error) {
                console.log(error);
            });
    };



    // Using axios Library. https://www.npmjs.com/package/axios
    /*axiosGet() {
        this._axios.get('/user?ID=12345')
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    }

    axiosGet2() {
        // Optionally the request above could also be done as
        this._axios.get('/user', {
                params: {
                    ID: 12345
                }
            })
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    }*/
}


// Private module functions
function checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response;
    } else {
        const error = new Error(`HTTP Error ${response.statusText}`);
        error.status = response.statusText;
        error.response = response;
        console.log(error);
        throw error;
    }
}

function parseJSON(response) {
    return response.json();
}


// Export singleton Service Class
export default new LemaApi();