Home Reference Source

application/util/request.js

import URI from 'urijs';
import _ from 'lodash';

/**
 * Request class is similar to those in other frameworks
 * allowing easy, quick access to param info.
 */
class Request {

    /**
     * Return current Uri string (sans domain)
     * @return {string}
     */
    getPath() {
        const uri = this._getUri();
        const frag = uri.fragment(true);

        return frag.pathname();
    }

    /**
     * Return query as object or string
     * @param  {Boolean} asString True, return as string (default), false as object
     * @return {mixed}           String or object
     */
    getQuery(asString = true) {
        const uri = this._getUri();

        if (asString) {
            return uri.query();
        } else {
            return uri.query(true);
        }
    }

    /**
     * Shallow clone query with updated params.
     * Will de-duplicate and return as string
     * This will not replace the existing query string.
     *
     * @param {object} obj New/updated query params
     * @return {string} updated query
     */
    setQuery(obj) {
        const query = this.getQuery(false);

        const newQuery = URI.buildQuery(_.defaults(obj, query));

        return URI(newQuery)
            .duplicateQueryParameters(false)
            .normalizeQuery()
            .toString();
    }

    /**
     * Return original URI object
     * @return {object} URI object
     */
    getUri() {
        return this._getUri();
    }

    /**
     * Returns original URI object. Allows for testing override
     * @return {object} URI
     */
    _getUri() {
        return new URI(this._getLocationHref());

    }

    /**
     * Private method to return href, makes it easier to test
     * @return {string}
     */
    _getLocationHref() {
        return window.location.href;
    }
}

export default (new Request);