Home Reference Source

application/services/draft-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 draft API service
 */
class DraftService extends BaseService {

    updateDraft(draft) {
        return draft;
    }

    /**
     * Fetch most recent draft
     * @param  {string}  srn         Content srn
     * @param  {object}  opts        Hash of query options
     */
    fetchOne(srn, opts = {}) {
        if (!opts.content) {
            opts.content = srn;
        }
        return (dispatch) => {
            return this.get('/v3/draft', opts)
                .then((data) => {
                    info('FetchOne returned', data);
                    if (data && data.size) {
                        this.updateDraft(data.first());
                    } else {
                        this.updateDraft(Immutable.Map());
                    }
                });
        };
    }

    /**
     * Create new draft item
     * @param  {string} srn        Content SRN
     * @param  {object}   data     Hash of draft data
     * @param  {Function} callback
     */
    create(srn, data, callback) {
        let opts = {
            content: srn
        };

        return (dispatch) => {
            return this.post('/v3/draft', data, opts)
                .then((data) => {
                    info('Create returned', data);
                    this.updateDraft(data.first());
                    if (callback) {
                        callback(data.first());
                    }
                })
                .catch((e) => {
                    ErrorService.add('error', 'Unable to create item. Usually this means you don\'t have the right permissions');
                });
        };
    }
}

const service = alt.createActions(DraftService);

/**
 * Draft Flux store. Tracks
 * <ul>
 *     <li>draft</li>
 * </ul>
 */
class DraftsStore {
    constructor() {
        this.state = {
            'draft': Immutable.Map(),
        };

        this.bindListeners({
            'handleUpdateDraft': service.UPDATE_DRAFT,
        });
    }

    handleUpdateDraft(draft) {
        this.setState({'draft': draft});
    }
}

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

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

        this.addActions('drafts', DraftService);
        this.addStore('drafts', DraftsStore);
    }
}

export {DraftFlux as default, service as DraftService, store as DraftsStore};