graphdb
Version:
Javascript client library supporting GraphDB and RDF4J REST API.
386 lines (367 loc) • 17.2 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 _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); }
function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); 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 BaseRepositoryClient = require('../repository/base-repository-client');
var HttpRequestBuilder = require('../http/http-request-builder');
var RepositoryService = require('../service/repository-service');
var StatementsService = require('../service/statements-service');
var QueryService = require('../service/query-service');
var UploadService = require('../service/upload-service');
var DownloadService = require('../service/download-service');
var ConsoleLogger = require('../logging/console-logger');
var RDFMimeType = require('../http/rdf-mime-type');
var StringUtils = require('../util/string-utils');
/**
* Transactional RDF repository client implementation realizing transaction
* specific operations.
*
* This client won't perform retries to multiple server endpoints due to when a
* transaction is started all operations must be performed to the server where
* it was started.
*
* The transaction is active until {@link #commit} or {@link #rollback} is
* invoked. After that each sequential request will result in an error.
*
* @class
* @author Mihail Radkov
* @author Svilen Velikov
*/
var TransactionalRepositoryClient = /*#__PURE__*/function (_BaseRepositoryClient) {
/**
* @param {RepositoryClientConfig} repositoryClientConfig
*/
function TransactionalRepositoryClient(repositoryClientConfig) {
var _this;
_classCallCheck(this, TransactionalRepositoryClient);
_this = _callSuper(this, TransactionalRepositoryClient, [repositoryClientConfig]);
_this.initServices();
_this.active = true;
return _this;
}
/**
* @inheritDoc
*/
_inherits(TransactionalRepositoryClient, _BaseRepositoryClient);
return _createClass(TransactionalRepositoryClient, [{
key: "getLogger",
value: function getLogger() {
return new ConsoleLogger({
name: 'TransactionalRepositoryClient'
});
}
/**
* Instantiates dependent services.
*/
}, {
key: "initServices",
value: function initServices() {
var httpRequestExecutor = this.execute.bind(this);
var parseExecutor = this.parse.bind(this);
this.repositoryService = new RepositoryService(httpRequestExecutor);
this.statementsService = new StatementsService(httpRequestExecutor, this.parserRegistry, parseExecutor);
this.queryService = new QueryService(httpRequestExecutor, parseExecutor);
this.uploadService = new UploadService(httpRequestExecutor);
this.downloadService = new DownloadService(httpRequestExecutor);
}
/**
* @inheritDoc
* @override
* @throws {Error} if the transaction has been committed or rollbacked
*/
}, {
key: "execute",
value: function execute(requestBuilder) {
if (!this.active) {
throw new Error('Transaction is inactive');
}
return _superPropGet(TransactionalRepositoryClient, "execute", this, 3)([requestBuilder]);
}
/**
* Updates the http request builder in the provided service request for
* executing requests in a transaction.
*
* @param {ServiceRequest} serviceRequest the request to mutate
* @param {string} action the transaction action
*/
}, {
key: "decorateServiceRequest",
value: function decorateServiceRequest(serviceRequest, action) {
var requestBuilder = serviceRequest.getHttpRequestBuilder();
requestBuilder.setMethod('put').setUrl('').addParam('action', action);
}
/**
* Retrieves the size of the repository during the transaction and its
* isolation level.
*
* Repository size is the amount of statements present.
*
* @param {string|string[]} [context] if provided, the size calculation will
* be restricted. Will be encoded as N-Triple if it is not already one
* @return {Promise<number>} a promise resolving to the size of the repo
*/
}, {
key: "getSize",
value: function getSize(context) {
var serviceRequest = this.repositoryService.getSize(context);
this.decorateServiceRequest(serviceRequest, 'SIZE');
return serviceRequest.execute();
}
/**
* Fetch rdf data from statements endpoint using provided parameters.
*
* The fetched data depends on the transaction isolation level.
*
* 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 {Promise<string|Quad>} resolves with plain string or Quad according
* to provided response type.
*/
}, {
key: "get",
value: function get(payload) {
var serviceRequest = this.statementsService.get(payload);
this.decorateServiceRequest(serviceRequest, 'GET');
return serviceRequest.execute();
}
/**
* Executes request to query a repository.
*
* @param {GetQueryPayload} payload is an object holding request parameters
*
* @return {Promise} the client can subscribe to the stream events and consume
* the emitted strings or Quads depending on the provided response type as
* soon as they are available.
* @throws {Error} if the payload is misconfigured
*/
}, {
key: "query",
value: function query(payload) {
var serviceRequest = this.queryService.query(payload);
this.decorateServiceRequest(serviceRequest, 'QUERY');
return serviceRequest.execute();
}
/**
* Executes a request with a SPARQL query to update repository data.
*
* @param {UpdateQueryPayload} payload request object containing the query
* @return {Promise<void>} promise that will be resolved if the update is
* successful or rejected in case of failure
* @throws {Error} if the payload is misconfigured
*/
}, {
key: "update",
value: function update(payload) {
var serviceRequest = this.queryService.update(payload);
this.decorateServiceRequest(serviceRequest, 'UPDATE');
return serviceRequest.execute();
}
/**
* 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 {Promise<void>} promise that will be resolved if the addition is
* successful or rejected 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) {
var serviceRequest = this.statementsService.add(payload);
this.decorateServiceRequest(serviceRequest, 'ADD');
return serviceRequest.execute();
}
/**
* 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 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 {Promise<void>} promise that will be resolved if the addition
* is successful or rejected in case of failure
*/
}, {
key: "addQuads",
value: function addQuads(quads, context, baseURI) {
var serviceRequest = this.statementsService.addQuads(quads, context, baseURI);
this.decorateServiceRequest(serviceRequest, 'ADD');
return serviceRequest.execute();
}
/**
* Deletes the statements in the provided Turtle or Trig formatted data.
*
* @param {string} data payload data in Turtle or Trig format
* @return {Promise<void>} promise resolving after the data has been deleted
* successfully
* @throws {Error} if no data is provided for deleting
*/
}, {
key: "deleteData",
value: function deleteData(data) {
var _this2 = this;
if (StringUtils.isBlank(data)) {
throw new Error('Turtle data is required when deleting statements');
}
var requestBuilder = HttpRequestBuilder.httpPut('').setData(data).setParams({
action: 'DELETE'
}).addContentTypeHeader(RDFMimeType.TRIG);
return this.execute(requestBuilder).then(function (response) {
_this2.logger.debug(_this2.getLogPayload(response, {
data: data
}), 'Deleted data');
});
}
/**
* Fetch rdf data from statements endpoint using provided parameters.
*
* The request is configured so that expected response should be a readable
* stream.
*
* Provided request params will be automatically converted to N-Triples if
* they are not already encoded as such.
*
* @param {GetStatementsPayload} payload is an object holding request params
*
* @return {Promise<WritableStream>} the client can subscribe to the readable
* stream events and consume the emitted strings depending on the provided
* response type as soon as they are available.
*/
}, {
key: "download",
value: function download(payload) {
var serviceRequest = this.downloadService.download(payload);
this.decorateServiceRequest(serviceRequest, 'GET');
return serviceRequest.execute();
}
/**
* Streams data to the repository from the provided readable stream.
*
* This method is useful for library client who wants to upload a big data set
* into the repository during a transaction
*
* @param {ReadableStream} readStream stream with the data to be uploaded
* @param {string} contentType is one of RDF mime type formats,
* application/x-rdftransaction' for a transaction document or
* application/x-www-form-urlencoded
* @param {NamedNode|string} [context] optional context to restrict the
* operation. Will be encoded as N-Triple if it is not already one
* @param {string} [baseURI] optional uri against which any relative URIs
* found in the data would be resolved.
*
* @return {Promise<void>} a promise that will be resolved when the stream has
* been successfully consumed by the server
*/
}, {
key: "upload",
value: function upload(readStream, contentType, context, baseURI) {
var serviceRequest = this.uploadService.upload(readStream, contentType, context, baseURI);
this.decorateServiceRequest(serviceRequest, 'ADD');
return serviceRequest.execute();
}
/**
* Uploads the file specified by the provided file path to the server.
*
* See {@link #upload}
*
* @param {string} filePath path to a file to be streamed to the server
* @param {string} contentType MIME type of the file's content
* @param {string|string[]} [context] restricts the operation 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 {Promise<void>} a promise that will be resolved when the file has
* been successfully consumed by the server
*/
}, {
key: "addFile",
value: function addFile(filePath, contentType, context, baseURI) {
var serviceRequest = this.uploadService.addFile(filePath, contentType, context, baseURI);
this.decorateServiceRequest(serviceRequest, 'ADD');
return serviceRequest.execute();
}
/**
* Commits the current transaction by applying any changes that have been
* sent to the server.
*
* This effectively makes the transaction inactive.
*
* @return {Promise<void>} that will be resolved after successful commit
*/
}, {
key: "commit",
value: function commit() {
var _this3 = this;
var requestBuilder = HttpRequestBuilder.httpPut('').setParams({
action: 'COMMIT'
});
return this.execute(requestBuilder).then(function (response) {
_this3.active = false;
_this3.logger.debug(_this3.getLogPayload(response), 'Transaction commit');
})["catch"](function (err) {
_this3.active = false;
return Promise.reject(err);
});
}
/**
* Rollbacks the current transaction reverting any changes in the server.
*
* This effectively makes the transaction inactive.
*
* @return {Promise<void>} that will be resolved after successful rollback
*/
}, {
key: "rollback",
value: function rollback() {
var _this4 = this;
var requestBuilder = HttpRequestBuilder.httpDelete('');
return this.execute(requestBuilder).then(function (response) {
_this4.active = false;
_this4.logger.debug(_this4.getLogPayload(response), 'Transaction rollback');
})["catch"](function (err) {
_this4.active = false;
return Promise.reject(err);
});
}
/**
* @return {boolean} <code>true</code> if the transaction is active or
* <code>false</code> otherwise
*/
}, {
key: "isActive",
value: function isActive() {
return this.active;
}
}]);
}(BaseRepositoryClient);
module.exports = TransactionalRepositoryClient;