Home Reference Source

application/services/base-service.js

import React from 'react';
import Immutable from 'immutable';

import ServiceFetchException from './../exceptions/service-fetch-exception';

import CurrentUser from './../current-user';

import {parameterize} from './../util/strings';
import {error} from './../util/console';

/**
 * Services extend the base service to provide
 * standard access methods.
 *
 * Keep in mind that the API uses Basic Auth
 * so the base service uses the CurrentUser object
 * to fetch and encode the key
 */
class BaseService {

    /**
     * Preform a GET action
     * @param  {string} url    URL
     * @param  {object} params Key/value parameters
     * @return {object}        Immutable map or list
     */
    get(url, params) {

        if (params) {
            url = url + '?' + parameterize(params);
        }

        return fetch(url, {
                'credentials': 'same-origin',
                'headers': {
                    'Authorization': 'Basic ' + btoa(CurrentUser.privateToken() + ':')
                }
            })
            .then((r) => {
                if (r.status !== 200) {
                    throw new ServiceFetchException({
                        method: 'GET',
                        response: r,
                        url: url,
                        body: params
                    });
                }
                return r.json();
            })
            .then((data) => Immutable.fromJS(data));
    }

    /**
     * Preform a POST action
     * @param  {string} url  URL
     * @param  {object} data   Key/value POST data
     * @param  {object} params Key/value GET data
     * @return {object}      Immutable map or list
     */
    post(url, data, params = null) {
        if (params) {
            url = url + '?' + parameterize(params);
        }

        return fetch(url, {
                'credentials': 'same-origin',
                'method': 'post',
                'headers': {
                    'Content-Type': 'application/json',
                    'Authorization': 'Basic ' + btoa(CurrentUser.privateToken() + ':')
                },
                'body': JSON.stringify(data)

            })
            .then((r) => {
                if (r.status !== 200) {
                    throw new ServiceFetchException({
                        method: 'POST',
                        response: r,
                        url: url,
                        body: data
                    });
                }
                return r.json();
            })
            .then((data) => Immutable.fromJS(data));
    }

    /**
     * Preform a PUT action
     * @param  {string} url  URL
     * @param  {object} data Key/value data
     * @return {object}      Immutable map or list
     */
    put(url, data) {
        return fetch(url, {
                'credentials': 'same-origin',
                'method': 'put',
                'headers': {
                    'Content-Type': 'application/json',
                    'Authorization': 'Basic ' + btoa(CurrentUser.privateToken() + ':')
                },
                'body': JSON.stringify(data)

            })
            .then((r) => {
                if (!r.ok || r.status !== 200) {
                    throw new ServiceFetchException({
                        method: 'PUT',
                        response: r,
                        url: url,
                        body: data
                    });
                }
                return r.json();
            })
            .then((data) => Immutable.fromJS(data));
    }

    /**
     * Preform a DELETE action
     * @param  {string} url URL
     * @return {object}     Immutable map or list
     */
    delete(url, data = {}) {
        return fetch(url, {
                'credentials': 'same-origin',
                'method': 'delete',
                'headers': {
                    'Content-Type': 'application/json',
                    'Authorization': 'Basic ' + btoa(CurrentUser.privateToken() + ':')
                },
                'body': JSON.stringify(data)
            })
            .then((r) => {
                if (r.status !== 200) {
                    throw new ServiceFetchException({
                        method: 'DELETE',
                        response: r,
                        url: url
                    });
                }
                return r.json();
            });
    }

    /**
     * Preform a POST action
     * @param  {string} url  URL
     * @param  {object} data   Key/value POST data
     * @param  {object} params Key/value GET data
     * @return {object}      Immutable map or list
     */
    postUpload(url, data, params = null) {
        if (params) {
            url = url + '?' + parameterize(params);
        }

        let formData = new FormData();
        for(let name in data) {
            if (name == 'file') {
                continue;
            }
            formData.append(name, data[name]);
        }

        formData.append('file', data['file'], data['slug']);

        return fetch(url, {
                'credentials': 'same-origin',
                'method': 'post',
                'headers': {
                    'Authorization': 'Basic ' + btoa(CurrentUser.privateToken() + ':')
                },
                'body': formData

            })
            .then((r) => {
                if (r.status !== 200) {
                    throw new ServiceFetchException({
                        method: 'POST',
                        response: r,
                        url: url,
                        body: data
                    });
                }
                return r.json();
            })
            .then((data) => Immutable.fromJS(data));
    }
}

export default BaseService;