Home Reference Source

application/services/author-service.js

import Immutable from 'immutable';

import alt from './../alt';
import Alt from 'alt';
import BaseService from './base-service';
import {ErrorService} from './error-service';

import {parseSrn} from './../util/strings';
import {info} from './../util/console';

/**
 * Interact with author API service
 */
class AuthorService extends BaseService {

    updateAuthor(author) {
        return author;
    }

    updateAuthors(authors) {
        return authors;
    }

    updatePagination(pagination) {
        return pagination;
    }
    
    reset() {
        return (dispatch) => {
            setTimeout(() => {
                this.updateAuthors(Immutable.fromJS([]));
            }, 1);
        }
    }

    /**
     * Run a query on the search endpoint. See search docs for query info
     * @param  {object} opts Query has
     */
    search(opts) {
        if (opts && !opts.type) {
            opts.type = 'author';
        }
        
        return (dispatch) => {
            return this.get('/v3/search', opts)
                .then((data) => {
                    info('Search returned', data);
                    this.updateAuthors(data.get('items'))
                });
        };
    }

    /**
     * Remove (delete) author
     * @param  {string} id
     */
    remove(id) {
        return (dispatch) => {
            return this.delete('/v3/author/' + id)
                .then(() => {
                    info(arguments);
                })
                .catch((e) => {
                    ErrorService.add('error', 'Unable to delete author, usually this means you don\'t have permission to remove items.');
                });
        };
    }

    /**
     * Update existing author
     * @param  {string}   id       UUID
     * @param  {object}   data     Hash of author data
     * @param  {Function} callback
     */
    update(id, data, callback) {
        return (dispatch) => {
            return this.put('/v3/author/' + id, data)
                .then((data) => {
                    info('Update returned', data);
                    this.updateAuthor(data.first());
                    if (callback) {
                        callback(data.first());
                    }
                })
                .catch((e) => {
                    ErrorService.add('error', 'Unable to save author, usually this means you don\'t have it checked out.');
                });
        }
    }

    /**
     * Create new author
     * @param  {object}   data     Hash of content data
     * @param  {Function} callback
     */
    create(data, callback) {
        return (dispatch) => {
            return this.post('/v3/author/', data)
                .then((data) => {
                    info('Create returned', data);
                    this.updateAuthor(data.first());
                    if (callback) {
                        callback(data.first());
                    }
                })
                .catch((e) => {
                    ErrorService.add('error', 'Unable to save author, usually this means you don\'t have it checked out.');
                });
        };
    }

    /**
     * Fetch single author
     * @param  {string}  id          UUID
     * @param  {object}  opts        Hash of query options
     * @param  {Boolean} forceUpdate If true (default) force update to store, otherwise, don't
     */
    fetchOne(id, opts, forceUpdate = true) {
        if (forceUpdate === true) {
            this.updateAuthor([]);
        }
        return (dispatch) => {
            return this.get('/v3/author/' + id, opts)
                .then((data) => {
                    info('FetchOne returned', data);
                    this.updateAuthor(data.first());
                });
        };
    }

    /**
     * Fetch paginated author items
     * @param  {object} opts Hash of query options
     */
    fetch(opts) {
        return (dispatch) => {
            return this.get('/v3/author', opts)
                .then((data) => {
                    info('Fetch returned', data);
                    this.updatePagination(Immutable.fromJS({
                        'first': data.get('first'),
                        'before': data.get('before'),
                        'current': data.get('current'),
                        'last': data.get('last'),
                        'next': data.get('next'),
                        'total_pages': data.get('total_pages'),
                        'total_items': data.get('total_items'),
                        'limit': data.get('limit')
                    }));
                    
                    if (data.get('items').size) {
                        this.updateAuthors(data.get('items'))
                    } else {
                        this.updateAuthors(Immutable.fromJS([]));
                    }
                });
        };
    }
}

const service = alt.createActions(AuthorService);

/**
 * Author Flux store. Tracks
 * <ul>
 *     <li>author</li>
 *     <li>authors</li>
 *     <li>pagination</li>
 * </ul>
 */
class AuthorsStore {
    constructor() {
        this.state = {
            'author': Immutable.Map(),
            'authors': Immutable.Map(),
            'pagination': Immutable.Map()
        };

        this.bindListeners({
            'handleUpdateAuthor': service.UPDATE_AUTHOR,
            'handleUpdateAuthors': service.UPDATE_AUTHORS,
            'handleUpdatePagination': service.UPDATE_PAGINATION
        });
    }

    handleUpdateAuthor(author) {
        this.setState({'author': author});
    }

    handleUpdateAuthors(authors) {
        this.setState({'authors': authors});
    }

    handleUpdatePagination(pagination) {
        this.setState({'pagination': pagination});
    }

}

const store = alt.createStore(AuthorsStore, 'AuthorsStore');

/**
 * Instace wrapper if you don't or can't use the singleton action and classes.
 *
 * Actions and store are both under the 'authors' key.
 */
class AuthorFlux extends Alt {
    constructor(config = {}) {
        super(config);

        this.addActions('authors', AuthorService);
        this.addStore('authors', AuthorsStore);
    }
}

export {AuthorFlux as default, service as AuthorService, store as AuthorsStore};