Home Reference Source

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

    updateVersion(version) {
        return version;
    }

    updateVersions(version) {
        return version;
    }

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

    /**
     * Fetch all versions for given UUID
     * @param {string} srn  valid content SRN
     * @param {object} opts hash of query options
     */
    fetch(srn = false, opts = {}) {
        if (!opts.content && srn) {
            opts.content = srn;
        }
        if (!opts.content) {
            throw 'SRN is required';
        }
        return (dispatch) => {
            return this.get('/v3/version', opts)
                .then((data) => {
                    info('Fetch returned', data);
                    this.updateVersions(data.get('items'))
                });
        };
    }
}

const service = alt.createActions(VersionService);

/**
 * Versions Flux store. Tracks
 * <ul>
 *     <li>version</li>
 *     <li>versions</li>
 * </ul>
 */
class VersionsStore {
    constructor() {
        this.state = {
            'version': Immutable.Map(),
            'versions': Immutable.Map()
        };

        this.bindListeners({
            'handleUpdateVersion': service.UPDATE_VERSION,
            'handleUpdateVersions': service.UPDATE_VERSIONS
        });
    }

    handleUpdateVersion(version) {
        this.setState({'version': version});
    }

    handleUpdateVersions(version) {
        this.setState({'versions': version});
    }
}

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

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

        this.addActions('versions', VersionService);
        this.addStore('versions', VersionsStore);
    }
}

export {VersionFlux as default, service as VersionService, store as VersionsStore};