graphdb
Version:
Javascript client library supporting GraphDB and RDF4J REST API.
170 lines (160 loc) • 6.61 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); }
var AuthenticationService = require('../service/authentication-service');
var HttpClient = require('../http/http-client');
var ConsoleLogger = require('../logging/console-logger');
var HttpResponse = require('../http/http-response');
// Imports used by TypeScript type generation
var ServerClientConfig = require('./server-client-config');
var HttpRequestBuilder = require('../http/http-request-builder');
var User = require('../auth/user');
/**
* Implementation of the server operations.
*
* If the server against which this client will be used has security enabled,
* then it should be configured with the username and password in the
* {@link ServerClientConfig}. In this case a login attempt is made before any
* API method to be executed. Upon successful login an {@link User} which holds
* the credentials and the authorization token in the context of the client is
* created. In all consecutive API calls the authorization token is sent as a
* http header.
*
* By default {@link ServerClientConfig} is configured with
* <code>keepAlive = true</code> which means that upon authorization token
* expiration current logged-in user would be re-logged automatically before
* next API call. This configuration can be changed within the configuration.
*
* @class
*
* @author Mihail Radkov
* @author Svilen Velikov
* @author Boyan Tonchev
*/
var Server = /*#__PURE__*/function () {
/**
* @param {ServerClientConfig} config for the server client.
**/
function Server(config) {
_classCallCheck(this, Server);
this.config = config;
this.initHttpClient();
this.initLogger();
this.authenticationService = new AuthenticationService(this.httpClient);
}
/**
* Initializes the http client.
*/
return _createClass(Server, [{
key: "initHttpClient",
value: function initHttpClient() {
this.httpClient = new HttpClient(this.config.getEndpoint()).setDefaultReadTimeout(this.config.getTimeout()).setDefaultWriteTimeout(this.config.getTimeout());
}
/**
* Initializes the logger.
*/
}, {
key: "initLogger",
value: function initLogger() {
this.logger = new ConsoleLogger({
name: 'Server',
serverURL: this.config.getEndpoint()
});
}
/**
* Executes http request wrapped in provided request builder.
* If the server config provides username and password, then a logging attempt
* is made. Upon successful login the auth data is stored for later requests.
*
* @public
*
* @param {HttpRequestBuilder} requestBuilder
*
* @return {Promise<HttpResponse|Error>} a promise which resolves to response
* wrapper or rejects with error if thrown during execution.
*/
}, {
key: "execute",
value: function execute(requestBuilder) {
var _this = this;
var startTime = Date.now();
return this.authenticationService.login(this.config, this.getLoggedUser()).then(function (user) {
_this.setLoggedUser(user);
_this.decorateRequestConfig(requestBuilder);
return _this.httpClient.request(requestBuilder);
}).then(function (response) {
var executionResponse = new HttpResponse(response, _this.httpClient);
executionResponse.setElapsedTime(Date.now() - startTime);
return executionResponse;
})["catch"](function (error) {
var status = error.response ? error.response.status : null;
// Unauthorized
if (status && status === 401 && _this.config.getKeepAlive()) {
// re-execute will try to re-login the user and update it
return _this.execute(requestBuilder);
}
return Promise.reject(error);
});
}
/**
* Performs a logout of logged-in user.
*
* This method normally shouldn't be called as it does nothing but just clears
* current authentication token. After that any consecutive API call against
* the secured server will throw <code>Unauthorized</code> error with status
* code <code>401</code> because the token is not sent any more, which in
* result will force re-login for the same user to be executed by default,
* unless the client is configured with
* <code>ServerClientConfig.keepAlive = false</code>
*
* @private
*
* @return {Promise} returns a promise which resolves with undefined.
*/
}, {
key: "logout",
value: function logout() {
return this.authenticationService.logout(this.getLoggedUser());
}
/**
* Allow request config to be altered before sending.
*
* @private
* @param {HttpRequestBuilder} requestBuilder
*/
}, {
key: "decorateRequestConfig",
value: function decorateRequestConfig(requestBuilder) {
var token = this.authenticationService.getAuthenticationToken(this.getLoggedUser());
if (token) {
requestBuilder.addAuthorizationHeader(token);
}
}
/**
* Logged user getter.
* @return {User} user
*/
}, {
key: "getLoggedUser",
value: function getLoggedUser() {
return this.user;
}
/**
* User setter
* @param {User} user
*
* @return {Server}
*/
}, {
key: "setLoggedUser",
value: function setLoggedUser(user) {
this.user = user;
return this;
}
}]);
}();
module.exports = Server;