all files / sparql/ transport.js

65.96% Statements 31/47
87.5% Branches 14/16
57.14% Functions 8/14
20% Lines 4/20
2 statements, 1 function, 5 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                                                                                                                                     
'use strict';
 
var http = require('http'),
    url = require('url'),
    Promise = require('bluebird');
 
import Result from './result';
 
export default class Transport {
    /**
     * Implements HTTP transport
     *
     * @class Transport
     * @constructor
     * @param {String} endpoint - SPARQL endpoint URL
     */
    constructor(endpoint) {
        this._endpoint = endpoint;
    }
 
    /**
     * Implements HTTP transport
     *
     * @method submit
     * @param {String} queryString - SPARQL query string
     * @returns {Promise} - Returns a Promise that will yield the Result object
     */
    submit(queryString) {
        var instance = this;
        return new Promise(function (resolve, reject) {
                var data = '', parsedUri = url.parse(instance._endpoint),
                    encodedQuery = `query=${encodeURIComponent(queryString)}`,
                    request = http.request({
                        method: 'POST',
                        hostname: parsedUri.hostname,
                        port: parsedUri.port,
                        path: parsedUri.path,
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'Accept': 'application/sparql-results+json',
                            'Content-Length': encodedQuery.length
                        }
                    }, function (response) {
                        response.setEncoding('utf8');
                        response.on('data', function (chunk) {
                            data += chunk;
                        });
                        response.on('end', function () {
                            if (response.statusCode === 200) {
                                resolve(data);
                            } else {
                                reject(new Error(data));
                            }
                        });
                    });
 
                request.on('error', reject);
 
                request.write(encodedQuery);
                request.end();
            })
            .then(function (data) {
                var result = new Result(JSON.parse(data));
                return result;
            })
            .catch(function (err) {
                throw new Error(`QBuilder query failed: ${err.message}`);
            });
    }
}