all files / sparql/ query.js

77.56% Statements 121/156
70.53% Branches 67/95
96.88% Functions 31/32
49.28% Lines 34/69
41 statements, 16 functions, 31 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
'use strict';
 
import Transport from './transport';
import Prefix from './prefix';
import GraphPattern from './graph-pattern';
import GroupGraphPattern from './group-graph-pattern';
import * as QueryTypes from './query-types';
 
export default class Query {
    /**
     * The Query is the root object for all SPARQL requests
     *
     * @class Query
     * @constructor
     * @param {String} endpoint - URL of the SPARQL endpoint
     */
    constructor(endpoint) {
        this.reset();
        this._transport = new Transport(endpoint);
    }
 
    /**
     * Sets the base IRI
     *
     * @method base
     * @param {String} content - BASE string
     */
    base(content) {
        this._config.base = content;
    }
 
    /**
     * Sets the prefix(es) for the query
     *
     * @method prefix
     * @param {Prefix|String|Array} content - A single Prefix string or object or an array of Prefix objects or strings
     * @returns {Query} - Returns current instance (chainable)
     */
    prefix(content) {
        this.addArrayOrSingle(content, this.addPrefix);
        return this;
    }
 
    /**
     * Add a prefix to the query
     *
     * @method addPrefix
     * @param {Prefix|String|Array} content - A single Prefix string or object
     */
    addPrefix(content) {
        if (content instanceof Prefix) {
            this._config.prefixes.push(content);
        } else if (typeof content === 'string') {
            this._config.prefixes.push(new Prefix(content));
        }
    }
 
    /**
     * Get the Prefix objects of the Query
     *
     * @method getPrefixes
     * @returns {Array}
     */
    getPrefixes() {
        return this._config.prefixes;
    }
 
    /**
     * Remove all Prefixes from the Query
     *
     * @method clearPrefixes
     */
    clearPrefixes() {
        this._config.prefixes = [];
    }
 
    /**
     * Set the current query to SELECT
     *
     * @method select
     * @param {String} content - Arguments given to the SELECT statement
     * @param {String} modifier - Optional modifier to be added (e.g. DISTINCT)
     * @returns {Query} - Returns current instance (chainable)
     */
    select(content, modifier) {
        this._config.query = new QueryTypes.Select(content, modifier);
        return this;
    }
 
    /**
     * Set the current query to DESCRIBE
     *
     * @method describe
     * @param {String} content - Arguments given to the DESCRIBE statement
     * @returns {Query} - Returns current instance (chainable)
     */
    describe(content) {
        this._config.query = new QueryTypes.Describe(content);
        return this;
    }
 
    /**
     * Set the current query to ASK
     *
     * @method ask
     * @returns {Query} - Returns current instance (chainable)
     */
    ask() {
        this._config.query = new QueryTypes.Ask();
        return this;
    }
 
    /**
     * Set the current query to CONSTRUCT
     *
     * @method construct
     * @param {Triple|Array} triples - One or more Triples to be used for a DESCRIBE GraphPattern
     * @returns {Query} - Returns current instance (chainable)
     */
    construct(triples) {
        this._config.query = new QueryTypes.Construct(triples);
        return this;
    }
 
    /**
     * Set dataset clause
     *
     * @method from
     * @param {String|Array} content - One or more strings with dataset clauses (without FROM or NAMED)
     * @param {Boolean} named - Optional flag to set clause to NAMED
     * @returns {Query} - Returns current instance (chainable)
     */
    from(content, named = false) {
        this.addArrayOrSingle(content, (element) => {
            this._config.datasetClause.push(`FROM${named ? ' NAMED' : ''} ${element}`);
        });
        return this;
    }
 
    /**
     * Get current dataset clauses
     *
     * @method getDatasetClauses
     * @returns {Array}
     */
    getDatasetClauses() {
        return this._config.datasetClause;
    }
 
    /**
     * Clear current dataset clauses
     *
     * @method clearDatasetClauses
     */
    clearDatasetClauses() {
        this._config.datasetClause = [];
    }
 
    /**
     * Set where clause
     *
     * @method where
     * @param {String|Array} content - A GraphPattern or a GroupGraphPattern object
     * @returns {Query} - Returns current instance (chainable)
     */
    where(content) {
        Eif (content instanceof GraphPattern ||
            content instanceof GroupGraphPattern) {
            this._config.whereClause = content;
        } else {
            throw new Error('TypeError: Where clause must be a graph pattern.');
        }
        return this;
    }
 
    /**
     * Get current where clause
     *
     * @method getWhereClause
     * @returns {GraphPattern|GroupGraphPattern}
     */
    getWhereClause() {
        return this._config.whereClause;
    }
 
    /**
     * Set order for query
     *
     * @method order
     * @param {String} content - Order string without ORDER BY
     * @returns {Query} - Returns current instance (chainable)
     */
    order(content) {
        Eif (typeof content === 'string') {
            this._config.solutionModifiers.push(`ORDER BY ${content}`);
        } else {
            throw new Error(`Input for ORDER must be string but is ${typeof content}.`);
        }
        return this;
    }
 
    /**
     * Set limit for query
     *
     * @method limit
     * @param {Number} count - Limit count
     * @returns {Query} - Returns current instance (chainable)
     */
    limit(count) {
        Eif (typeof count === 'number') {
            this._config.solutionModifiers.push(`LIMIT ${count}`);
        } else {
            throw new Error(`Input for LIMIT must be number but is ${typeof count}.`);
        }
        return this;
    }
 
    /**
     * Set limit for offset
     *
     * @method offset
     * @param {Number} count - Offset count
     * @returns {Query} - Returns current instance (chainable)
     */
    offset(count) {
        Eif (typeof count === 'number') {
            this._config.solutionModifiers.push(`OFFSET ${count}`);
        } else {
            throw new Error(`Input for OFFSET must be number but is ${typeof count}.`);
        }
        return this;
    }
 
    /**
     * Execute query
     *
     * @method exec
     * @returns {Promise} - Returns a Promise with will yield a Result object
     */
    exec() {
        return this._transport.submit(this.toString());
    }
 
    /**
     * Retrieves the SPARQL string representation of the current instance, adding the FILTER keyword.
     *
     * @method toString
     * @param {Boolean} isSubquery - If set, skips the BASE and PREFIX parts for inclusion as a subquery
     * @returns {String}
     */
    toString(isSubQuery = false) {
        var queryString = '';
 
        if (!isSubQuery) {
            Iif (this._config.base) {
                queryString += `BASE ${this._config.base}`;
            }
 
            Iif (this._config.prefixes.length > 0) {
                for (let prefix of this._config.prefixes) {
                    queryString += `${prefix.toString()} `;
                }
            }
        }
 
        if (this._config.query) {
            queryString += this._config.query.toString();
        } else {
            throw new Error(`TypeError: Query type must be defined.`);
        }
 
        Eif (Array.isArray(this._config.datasetClause)) {
            queryString += `${this._config.datasetClause.join(' ')} `;
        } else {
            throw new Error(`TypeError: Dataset clause should be array but is ${typeof this._config.datasetClause}`);
        }
 
        Eif (this._config.whereClause) {
            queryString += `WHERE ${this._config.whereClause.toString()}`;
        } else {
            throw new Error(`TypeError: Where clause is not defined!`);
        }
 
        Eif (Array.isArray(this._config.solutionModifiers)) {
            for (let mod of this._config.solutionModifiers) {
                queryString += ` ${mod.toString()}`;
            }
        }
 
        return queryString;
    }
 
    /**
     * Reset query (endpoint setting stays)
     *
     * @method reset
     */
    reset() {
        this._config = {
            base: null,
            prefixes: [],
            query: null,
            subQueries: [],
            datasetClause: [],
            whereClause: null,
            solutionModifiers: []
        };
    }
 
    addArrayOrSingle(content, addFunction) {
        if (Array.isArray(content)) {
            for (var element of content) {
                addFunction(element);
            }
        } else {
            addFunction(content);
        }
    }
}