graphdb
Version:
Javascript client library supporting GraphDB and RDF4J REST API.
305 lines (295 loc) • 14.5 kB
JavaScript
;
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var Service = require('./service');
var HttpRequestBuilder = require('../http/http-request-builder');
var ServiceRequest = require('./service-request');
var PATH_STATEMENTS = require('./service-paths').PATH_STATEMENTS;
var RDFMimeType = require('../http/rdf-mime-type');
var StringUtils = require('../util/string-utils');
var TermConverter = require('../model/term-converter');
var LoggingUtils = require('../logging/logging-utils');
var CommonUtils = require('../util/common-utils');
/**
* Service for reading, inserting or deleting repository statements.
*
* @author Mihail Radkov
* @author Svilen Velikov
*/
var StatementsService = /*#__PURE__*/function (_Service) {
/**
* Instantiates the service with the supplied executor and parser utils.
*
* @param {Function} httpRequestExecutor executor for HTTP requests
* @param {ParserRegistry} parserRegistry registry of available parsers
* @param {Function} parseExecutor function that will parse provided data
*/
function StatementsService(httpRequestExecutor, parserRegistry, parseExecutor) {
var _this;
_classCallCheck(this, StatementsService);
_this = _callSuper(this, StatementsService, [httpRequestExecutor]);
_this.parserRegistry = parserRegistry;
_this.parseExecutor = parseExecutor;
return _this;
}
/**
* Fetch rdf data from statements endpoint using provided parameters.
*
* Provided values will be automatically converted to N-Triples if they are
* not already encoded as such.
*
* @param {GetStatementsPayload} payload is an object holding the request
* parameters.
*
* @return {ServiceRequest} service request that resolves to plain string or
* Quad according to provided response type.
*/
_inherits(StatementsService, _Service);
return _createClass(StatementsService, [{
key: "get",
value: function get(payload) {
var _this2 = this;
var requestBuilder = HttpRequestBuilder.httpGet(PATH_STATEMENTS).setParams({
subj: TermConverter.toNTripleValue(payload.getSubject()),
pred: TermConverter.toNTripleValue(payload.getPredicate()),
obj: TermConverter.toNTripleValue(payload.getObject()),
context: TermConverter.toNTripleValues(payload.getContext()),
infer: payload.getInference()
}).addAcceptHeader(payload.getResponseType());
var parser = this.parserRegistry.get(payload.getResponseType());
if (parser && parser.isStreaming()) {
requestBuilder.setResponseType('stream');
}
return new ServiceRequest(requestBuilder, function () {
return _this2.httpRequestExecutor(requestBuilder).then(function (response) {
_this2.logger.debug(LoggingUtils.getLogPayload(response, {
subject: payload.getSubject(),
predicate: payload.getPredicate(),
object: payload.getObject(),
context: payload.getContext()
}), 'Fetched data');
return _this2.parseExecutor(response.getData(), payload.getResponseType());
});
});
}
/**
* Saves the provided statement payload in the repository.
*
* The payload will be converted to a quad or a collection of quads in case
* there are multiple contexts.
*
* After the conversion, the produced quad(s) will be serialized to Turtle or
* Trig format and send to the repository as payload.
*
* See {@link #addQuads()}.
*
* @param {AddStatementPayload} payload holding request parameters
*
* @return {ServiceRequest} service request that will resolve if the addition
* is successful or reject in case of failure
*
* @throws {Error} if the payload is not provided or the payload has null
* subject, predicate and/or object
*/
}, {
key: "add",
value: function add(payload) {
if (!payload) {
throw new Error('Cannot add statement without payload');
}
var subject = payload.getSubject();
var predicate = payload.getPredicate();
var object = payload.getObject();
var context = payload.getContext();
if (CommonUtils.hasNullArguments(subject, predicate, object)) {
throw new Error('Cannot add statement with null ' + 'subject, predicate or object');
}
var quads;
if (payload.isLiteral()) {
quads = TermConverter.getLiteralQuads(subject, predicate, object, context, payload.getDataType(), payload.getLanguage());
} else {
quads = TermConverter.getQuads(subject, predicate, object, context);
}
return this.addQuads(quads, payload.getContext(), payload.getBaseURI());
}
/**
* Serializes the provided quads to Turtle format and sends them to the
* repository as payload.
*
* If any of the quads have a graph, then the text will be serialized to the
* Trig format which is an extended version of Turtle supporting contexts.
*
* @param {Quad[]} quads collection of quads to be sent as Turtle/Trig text
* @param {string|string[]} [context] restricts the insertion to the given
* context. Will be encoded as N-Triple if it is not already one
* @param {string} [baseURI] used to resolve relative URIs in the data
*
* @return {ServiceRequest} service request that will be resolved if the
* addition is successful or rejected in case of failure
*
* @throws {Error} if no quads are provided or if they cannot be converted
*/
}, {
key: "addQuads",
value: function addQuads(quads, context, baseURI) {
var _this3 = this;
var requestBuilder = this.getInsertRequest(quads, context, baseURI, false);
return new ServiceRequest(requestBuilder, function () {
return _this3.httpRequestExecutor(requestBuilder).then(function (response) {
_this3.logger.debug(LoggingUtils.getLogPayload(response, {
quads: quads,
context: context,
baseURI: baseURI
}), 'Inserted statements');
});
});
}
/**
* Overwrites the repository's data by serializing the provided quads to
* Turtle format and sending them to the repository as payload.
*
* If any of the quads have a graph, then the text will be serialized to the
* Trig format which is an extended version of Turtle supporting contexts.
*
* The overwrite will be restricted if the context parameter is specified.
*
* @param {Quad[]} quads collection of quads to be sent as Turtle/Trig text
* @param {string|string[]} [context] restricts the insertion to the given
* context. Will be encoded as N-Triple if it is not already one
* @param {string} [baseURI] used to resolve relative URIs in the data
*
* @return {ServiceRequest} service request that will be resolved if the
* overwrite is successful or rejected in case of failure
*
* @throws {Error} if no quads are provided or if they cannot be converted
*/
}, {
key: "putQuads",
value: function putQuads(quads, context, baseURI) {
var _this4 = this;
var requestBuilder = this.getInsertRequest(quads, context, baseURI, true);
return new ServiceRequest(requestBuilder, function () {
return _this4.httpRequestExecutor(requestBuilder).then(function (response) {
_this4.logger.debug(LoggingUtils.getLogPayload(response, {
quads: quads,
context: context,
baseURI: baseURI
}), 'Overwritten statements');
});
});
}
/**
* Constructs HttpRequestBuilder from the provided parameters for saving or
* overwriting statements.
*
* @private
*
* @param {Quad[]} quads collection of quads to be sent as Turtle/Trig text
* @param {string|string[]} [context] restricts the insertion to the given
* context. Will be encoded as N-Triple if it is not already one
* @param {string} [baseURI] used to resolve relative URIs in the data
* @param {boolean} overwrite defines if the data should overwrite the repo
* data or not
*
* @return {HttpRequestBuilder} promise resolving after the data has
* been inserted successfully or an error if not
*
* @throws {Error} if no quads are provided or if they cannot be converted
*/
}, {
key: "getInsertRequest",
value: function getInsertRequest(quads, context, baseURI, overwrite) {
var converted = TermConverter.toString(quads);
if (StringUtils.isBlank(converted)) {
throw new Error('Turtle/trig data is required when adding statements');
}
var requestBuilder = new HttpRequestBuilder().setUrl(PATH_STATEMENTS).setData(converted).addContentTypeHeader(RDFMimeType.TRIG).setParams({
baseURI: baseURI,
context: TermConverter.toNTripleValues(context)
});
if (overwrite) {
requestBuilder.setMethod('put');
} else {
requestBuilder.setMethod('post');
}
return requestBuilder;
}
/**
* Deletes statements in the repository based on the provided subject,
* predicate, object and or contexts. Each of them is optional and acts as
* statements filter which effectively narrows the scope of the deletion.
*
* Providing context or contexts will restricts the operation to one or more
* specific contexts in the repository.
*
* Provided values will be automatically converted to N-Triples if they are
* not already encoded as such.
*
* @param {String} [subject] resource subject
* @param {String} [predicate] resource predicate
* @param {String} [object] resource object
* @param {String[]|String} [contexts] resource or resources context
*
* @return {ServiceRequest} service request that will be resolved if the
* deletion is successful or rejected in case of failure
*/
}, {
key: "deleteStatements",
value: function deleteStatements(subject, predicate, object, contexts) {
var _this5 = this;
var requestBuilder = HttpRequestBuilder.httpDelete(PATH_STATEMENTS).setParams({
subj: TermConverter.toNTripleValue(subject),
pred: TermConverter.toNTripleValue(predicate),
obj: TermConverter.toNTripleValue(object),
context: TermConverter.toNTripleValues(contexts)
});
return new ServiceRequest(requestBuilder, function () {
return _this5.httpRequestExecutor(requestBuilder).then(function (response) {
_this5.logger.debug(LoggingUtils.getLogPayload(response, {
subject: subject,
predicate: predicate,
object: object,
contexts: contexts
}), 'Deleted statements');
});
});
}
/**
* Deletes all statements in the repository.
*
* @return {ServiceRequest} service request that will be resolved if the
* deletion is successful or rejected in case of failure
*/
}, {
key: "deleteAllStatements",
value: function deleteAllStatements() {
var _this6 = this;
var requestBuilder = HttpRequestBuilder.httpDelete(PATH_STATEMENTS);
return new ServiceRequest(requestBuilder, function () {
return _this6.httpRequestExecutor(requestBuilder).then(function (response) {
_this6.logger.debug(LoggingUtils.getLogPayload(response), 'Deleted all statements');
});
});
}
/**
* @inheritDoc
*/
}, {
key: "getServiceName",
value: function getServiceName() {
return 'StatementsService';
}
}]);
}(Service);
module.exports = StatementsService;