neo4j-driver
Advanced tools
Comparing version 2.0.0-alpha03 to 3.4.0-alpha01
/** | ||
* Copyright (c) 2002-2019 "Neo4j," | ||
* Copyright (c) "Neo4j" | ||
* Neo4j Sweden AB [http://neo4j.com] | ||
@@ -22,3 +22,3 @@ * | ||
var statement = [ | ||
var query = [ | ||
'MERGE (alice:Person {name:{name_a},age:{age_a}})', | ||
@@ -40,3 +40,3 @@ 'MERGE (bob:Person {name:{name_b},age:{age_b}})', | ||
var streamSession = driver.session() | ||
var streamResult = streamSession.run(statement.join(' '), params) | ||
var streamResult = streamSession.run(query.join(' '), params) | ||
streamResult.subscribe({ | ||
@@ -63,3 +63,3 @@ onNext: function (record) { | ||
var promiseSession = driver.session() | ||
var promiseResult = promiseSession.run(statement.join(' '), params) | ||
var promiseResult = promiseSession.run(query.join(' '), params) | ||
promiseResult | ||
@@ -66,0 +66,0 @@ .then(function (records) { |
"use strict"; | ||
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports["default"] = exports.WRITE = exports.READ = exports.Driver = void 0; | ||
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); | ||
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); | ||
var _session = _interopRequireDefault(require("./session")); | ||
var _pool = _interopRequireDefault(require("./internal/pool")); | ||
var _connectionChannel = _interopRequireDefault(require("./internal/connection-channel")); | ||
var _error = require("./error"); | ||
var _connectionProviderDirect = _interopRequireDefault(require("./internal/connection-provider-direct")); | ||
var _bookmark = _interopRequireDefault(require("./internal/bookmark")); | ||
var _connectivityVerifier = _interopRequireDefault(require("./internal/connectivity-verifier")); | ||
var _poolConfig = _interopRequireWildcard(require("./internal/pool-config")); | ||
var _logger = _interopRequireDefault(require("./internal/logger")); | ||
var _connectionErrorHandler = _interopRequireDefault(require("./internal/connection-error-handler")); | ||
var _constants = require("./internal/constants"); | ||
/** | ||
* Copyright (c) 2002-2019 "Neo4j," | ||
* Copyright (c) "Neo4j" | ||
* Neo4j Sweden AB [http://neo4j.com] | ||
@@ -56,24 +20,31 @@ * | ||
*/ | ||
var DEFAULT_MAX_CONNECTION_LIFETIME = 60 * 60 * 1000; // 1 hour | ||
/** | ||
* Constant that represents read session access mode. | ||
* Should be used like this: `driver.session({ defaultAccessMode: neo4j.session.READ })`. | ||
* @type {string} | ||
*/ | ||
var READ = _constants.ACCESS_MODE_READ; | ||
/** | ||
* Constant that represents write session access mode. | ||
* Should be used like this: `driver.session({ defaultAccessMode: neo4j.session.WRITE })`. | ||
* @type {string} | ||
*/ | ||
var __extends = (this && this.__extends) || (function () { | ||
var extendStatics = function (d, b) { | ||
extendStatics = Object.setPrototypeOf || | ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || | ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; | ||
return extendStatics(d, b); | ||
}; | ||
return function (d, b) { | ||
if (typeof b !== "function" && b !== null) | ||
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); | ||
extendStatics(d, b); | ||
function __() { this.constructor = d; } | ||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); | ||
}; | ||
})(); | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.WRITE = exports.READ = exports.Driver = void 0; | ||
var neo4j_driver_core_1 = require("neo4j-driver-core"); | ||
var session_rx_1 = __importDefault(require("./session-rx")); | ||
var FETCH_ALL = neo4j_driver_core_1.internal.constants.FETCH_ALL; | ||
var READ = neo4j_driver_core_1.driver.READ, WRITE = neo4j_driver_core_1.driver.WRITE; | ||
exports.READ = READ; | ||
var WRITE = _constants.ACCESS_MODE_WRITE; | ||
exports.WRITE = WRITE; | ||
var idGenerator = 0; | ||
/** | ||
* A driver maintains one or more {@link Session}s with a remote | ||
* Neo4j instance. Through the {@link Session}s you can send statements | ||
* Neo4j instance. Through the {@link Session}s you can send queries | ||
* and retrieve results from the database. | ||
@@ -86,68 +57,9 @@ * | ||
*/ | ||
var Driver = | ||
/*#__PURE__*/ | ||
function () { | ||
/** | ||
* You should not be calling this directly, instead use {@link driver}. | ||
* @constructor | ||
* @param {ServerAddress} address | ||
* @param {string} userAgent | ||
* @param {object} authToken | ||
* @param {object} config | ||
* @protected | ||
*/ | ||
function Driver(address, userAgent) { | ||
var authToken = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; | ||
(0, _classCallCheck2["default"])(this, Driver); | ||
sanitizeConfig(config); | ||
this._id = idGenerator++; | ||
this._address = address; | ||
this._userAgent = userAgent; | ||
this._authToken = authToken; | ||
this._config = config; | ||
this._log = _logger["default"].create(config); | ||
/** | ||
* Reference to the connection provider. Initialized lazily by {@link _getOrCreateConnectionProvider}. | ||
* @type {ConnectionProvider} | ||
* @protected | ||
*/ | ||
this._connectionProvider = null; | ||
this._afterConstruction(); | ||
} | ||
/** | ||
* @protected | ||
*/ | ||
(0, _createClass2["default"])(Driver, [{ | ||
key: "_afterConstruction", | ||
value: function _afterConstruction() { | ||
this._log.info("Direct driver ".concat(this._id, " created for server address ").concat(this._address)); | ||
var Driver = /** @class */ (function (_super) { | ||
__extends(Driver, _super); | ||
function Driver() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
} | ||
/** | ||
* Verifies connectivity of this driver by trying to open a connection with the provided driver options. | ||
* @param {string} [database=''] the target database to verify connectivity for. | ||
* @returns {Promise<object>} promise resolved with server info or rejected with error. | ||
*/ | ||
}, { | ||
key: "verifyConnectivity", | ||
value: function verifyConnectivity() { | ||
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, | ||
_ref$database = _ref.database, | ||
database = _ref$database === void 0 ? '' : _ref$database; | ||
var connectionProvider = this._getOrCreateConnectionProvider(); | ||
var connectivityVerifier = new _connectivityVerifier["default"](connectionProvider); | ||
return connectivityVerifier.verify({ | ||
database: database | ||
}); | ||
} | ||
/** | ||
* Acquire a session to communicate with the database. The session will | ||
* Acquire a reactive session to communicate with the database. The session will | ||
* borrow connections from the underlying connection pool as required and | ||
@@ -162,109 +74,39 @@ * should be considered lightweight and disposable. | ||
* | ||
* @param {string} [defaultAccessMode=WRITE] the access mode of this session, allowed values are {@link READ} and {@link WRITE}. | ||
* @param {string|string[]} [bookmarks=null] the initial reference or references to some previous | ||
* transactions. Value is optional and absence indicates that that the bookmarks do not exist or are unknown. | ||
* @param {string} [database=''] the database this session will connect to. | ||
* @return {Session} new session. | ||
* @public | ||
* @param {SessionConfig} config | ||
* @returns {RxSession} new reactive session. | ||
*/ | ||
}, { | ||
key: "session", | ||
value: function session() { | ||
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, | ||
_ref2$defaultAccessMo = _ref2.defaultAccessMode, | ||
defaultAccessMode = _ref2$defaultAccessMo === void 0 ? WRITE : _ref2$defaultAccessMo, | ||
bookmarkOrBookmarks = _ref2.bookmarks, | ||
_ref2$database = _ref2.database, | ||
database = _ref2$database === void 0 ? '' : _ref2$database; | ||
var sessionMode = Driver._validateSessionMode(defaultAccessMode); | ||
var connectionProvider = this._getOrCreateConnectionProvider(); | ||
var bookmark = bookmarkOrBookmarks ? new _bookmark["default"](bookmarkOrBookmarks) : _bookmark["default"].empty(); | ||
return new _session["default"]({ | ||
mode: sessionMode, | ||
database: database, | ||
connectionProvider: connectionProvider, | ||
bookmark: bookmark, | ||
config: this._config | ||
}); | ||
Driver.prototype.rxSession = function (_a) { | ||
var _b = _a === void 0 ? {} : _a, _c = _b.defaultAccessMode, defaultAccessMode = _c === void 0 ? WRITE : _c, bookmarks = _b.bookmarks, _d = _b.database, database = _d === void 0 ? '' : _d, fetchSize = _b.fetchSize, impersonatedUser = _b.impersonatedUser, bookmarkManager = _b.bookmarkManager; | ||
return new session_rx_1.default({ | ||
session: this._newSession({ | ||
defaultAccessMode: defaultAccessMode, | ||
bookmarkOrBookmarks: bookmarks, | ||
database: database, | ||
impersonatedUser: impersonatedUser, | ||
reactive: false, | ||
fetchSize: validateFetchSizeValue(fetchSize, this._config.fetchSize), | ||
bookmarkManager: bookmarkManager | ||
}), | ||
config: this._config | ||
}); | ||
}; | ||
return Driver; | ||
}(neo4j_driver_core_1.Driver)); | ||
exports.Driver = Driver; | ||
/** | ||
* @private | ||
*/ | ||
function validateFetchSizeValue(rawValue, defaultWhenAbsent) { | ||
var fetchSize = parseInt(rawValue, 10); | ||
if (fetchSize > 0 || fetchSize === FETCH_ALL) { | ||
return fetchSize; | ||
} | ||
}, { | ||
key: "_createConnectionProvider", | ||
// Extension point | ||
value: function _createConnectionProvider(address, userAgent, authToken) { | ||
return new _connectionProviderDirect["default"]({ | ||
id: this._id, | ||
config: this._config, | ||
log: this._log, | ||
address: address, | ||
userAgent: userAgent, | ||
authToken: authToken | ||
}); | ||
else if (fetchSize === 0 || fetchSize < 0) { | ||
throw new Error("The fetch size can only be a positive value or ".concat(FETCH_ALL, " for ALL. However fetchSize = ").concat(fetchSize)); | ||
} | ||
}, { | ||
key: "_getOrCreateConnectionProvider", | ||
value: function _getOrCreateConnectionProvider() { | ||
if (!this._connectionProvider) { | ||
this._connectionProvider = this._createConnectionProvider(this._address, this._userAgent, this._authToken); | ||
} | ||
return this._connectionProvider; | ||
else { | ||
return defaultWhenAbsent; | ||
} | ||
/** | ||
* Close all open sessions and other associated resources. You should | ||
* make sure to use this when you are done with this driver instance. | ||
* @return undefined | ||
*/ | ||
}, { | ||
key: "close", | ||
value: function close() { | ||
this._log.info("Driver ".concat(this._id, " closing")); | ||
if (this._connectionProvider) { | ||
this._connectionProvider.close(); | ||
} | ||
} | ||
}], [{ | ||
key: "_validateSessionMode", | ||
value: function _validateSessionMode(rawMode) { | ||
var mode = rawMode || WRITE; | ||
if (mode !== _constants.ACCESS_MODE_READ && mode !== _constants.ACCESS_MODE_WRITE) { | ||
throw (0, _error.newError)('Illegal session mode ' + mode); | ||
} | ||
return mode; | ||
} | ||
}]); | ||
return Driver; | ||
}(); | ||
/** | ||
* @private | ||
*/ | ||
exports.Driver = Driver; | ||
function sanitizeConfig(config) { | ||
config.maxConnectionLifetime = sanitizeIntValue(config.maxConnectionLifetime, DEFAULT_MAX_CONNECTION_LIFETIME); | ||
config.maxConnectionPoolSize = sanitizeIntValue(config.maxConnectionPoolSize, _poolConfig.DEFAULT_MAX_SIZE); | ||
config.connectionAcquisitionTimeout = sanitizeIntValue(config.connectionAcquisitionTimeout, _poolConfig.DEFAULT_ACQUISITION_TIMEOUT); | ||
} | ||
function sanitizeIntValue(rawValue, defaultWhenAbsent) { | ||
var sanitizedValue = parseInt(rawValue, 10); | ||
if (sanitizedValue > 0 || sanitizedValue === 0) { | ||
return sanitizedValue; | ||
} else if (sanitizedValue < 0) { | ||
return Number.MAX_SAFE_INTEGER; | ||
} else { | ||
return defaultWhenAbsent; | ||
} | ||
} | ||
var _default = Driver; | ||
exports["default"] = _default; | ||
exports.default = Driver; |
857
lib/index.js
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.driver = driver; | ||
Object.defineProperty(exports, "int", { | ||
enumerable: true, | ||
get: function get() { | ||
return _integer["int"]; | ||
} | ||
}); | ||
Object.defineProperty(exports, "isInt", { | ||
enumerable: true, | ||
get: function get() { | ||
return _integer.isInt; | ||
} | ||
}); | ||
Object.defineProperty(exports, "Neo4jError", { | ||
enumerable: true, | ||
get: function get() { | ||
return _error.Neo4jError; | ||
} | ||
}); | ||
Object.defineProperty(exports, "isPoint", { | ||
enumerable: true, | ||
get: function get() { | ||
return _spatialTypes.isPoint; | ||
} | ||
}); | ||
Object.defineProperty(exports, "isDate", { | ||
enumerable: true, | ||
get: function get() { | ||
return _temporalTypes.isDate; | ||
} | ||
}); | ||
Object.defineProperty(exports, "isDateTime", { | ||
enumerable: true, | ||
get: function get() { | ||
return _temporalTypes.isDateTime; | ||
} | ||
}); | ||
Object.defineProperty(exports, "isDuration", { | ||
enumerable: true, | ||
get: function get() { | ||
return _temporalTypes.isDuration; | ||
} | ||
}); | ||
Object.defineProperty(exports, "isLocalDateTime", { | ||
enumerable: true, | ||
get: function get() { | ||
return _temporalTypes.isLocalDateTime; | ||
} | ||
}); | ||
Object.defineProperty(exports, "isLocalTime", { | ||
enumerable: true, | ||
get: function get() { | ||
return _temporalTypes.isLocalTime; | ||
} | ||
}); | ||
Object.defineProperty(exports, "isTime", { | ||
enumerable: true, | ||
get: function get() { | ||
return _temporalTypes.isTime; | ||
} | ||
}); | ||
exports["default"] = exports.temporal = exports.spatial = exports.error = exports.session = exports.types = exports.logging = exports.auth = exports.integer = void 0; | ||
var _integer = _interopRequireWildcard(require("./integer")); | ||
var _graphTypes = require("./graph-types"); | ||
var _error = require("./error"); | ||
var _result = _interopRequireDefault(require("./result")); | ||
var _resultSummary = _interopRequireDefault(require("./result-summary")); | ||
var _record = _interopRequireDefault(require("./record")); | ||
var _driver = require("./driver"); | ||
var _routingDriver = _interopRequireDefault(require("./routing-driver")); | ||
var _version = _interopRequireDefault(require("./version")); | ||
var _util = require("./internal/util"); | ||
var _urlUtil = _interopRequireDefault(require("./internal/url-util")); | ||
var _spatialTypes = require("./spatial-types"); | ||
var _temporalTypes = require("./temporal-types"); | ||
var _serverAddress = _interopRequireDefault(require("./internal/server-address")); | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (g && (g = 0, op[0] && (_ = 0)), _) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Integer = exports.Point = exports.PathSegment = exports.Path = exports.UnboundRelationship = exports.Relationship = exports.Node = exports.Record = exports.ServerInfo = exports.Notification = exports.QueryStatistics = exports.ProfiledPlan = exports.Plan = exports.ResultSummary = exports.RxResult = exports.RxManagedTransaction = exports.RxTransaction = exports.RxSession = exports.Result = exports.ManagedTransaction = exports.Transaction = exports.Session = exports.Driver = exports.temporal = exports.spatial = exports.graph = exports.error = exports.session = exports.types = exports.logging = exports.auth = exports.isRetryableError = exports.Neo4jError = exports.integer = exports.isUnboundRelationship = exports.isRelationship = exports.isPathSegment = exports.isPath = exports.isNode = exports.isDateTime = exports.isLocalDateTime = exports.isDate = exports.isTime = exports.isLocalTime = exports.isDuration = exports.isPoint = exports.isInt = exports.int = exports.hasReachableServer = exports.driver = void 0; | ||
exports.bookmarkManager = exports.DateTime = exports.LocalDateTime = exports.Date = exports.Time = exports.LocalTime = exports.Duration = void 0; | ||
/** | ||
* Copyright (c) 2002-2019 "Neo4j," | ||
* Copyright (c) "Neo4j" | ||
* Neo4j Sweden AB [http://neo4j.com] | ||
@@ -119,62 +62,314 @@ * | ||
*/ | ||
var driver_1 = require("./driver"); | ||
Object.defineProperty(exports, "Driver", { enumerable: true, get: function () { return driver_1.Driver; } }); | ||
var version_1 = __importDefault(require("./version")); | ||
var neo4j_driver_core_1 = require("neo4j-driver-core"); | ||
Object.defineProperty(exports, "Neo4jError", { enumerable: true, get: function () { return neo4j_driver_core_1.Neo4jError; } }); | ||
Object.defineProperty(exports, "isRetryableError", { enumerable: true, get: function () { return neo4j_driver_core_1.isRetryableError; } }); | ||
Object.defineProperty(exports, "error", { enumerable: true, get: function () { return neo4j_driver_core_1.error; } }); | ||
Object.defineProperty(exports, "Integer", { enumerable: true, get: function () { return neo4j_driver_core_1.Integer; } }); | ||
Object.defineProperty(exports, "int", { enumerable: true, get: function () { return neo4j_driver_core_1.int; } }); | ||
Object.defineProperty(exports, "isInt", { enumerable: true, get: function () { return neo4j_driver_core_1.isInt; } }); | ||
Object.defineProperty(exports, "isPoint", { enumerable: true, get: function () { return neo4j_driver_core_1.isPoint; } }); | ||
Object.defineProperty(exports, "Point", { enumerable: true, get: function () { return neo4j_driver_core_1.Point; } }); | ||
Object.defineProperty(exports, "Date", { enumerable: true, get: function () { return neo4j_driver_core_1.Date; } }); | ||
Object.defineProperty(exports, "DateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.DateTime; } }); | ||
Object.defineProperty(exports, "Duration", { enumerable: true, get: function () { return neo4j_driver_core_1.Duration; } }); | ||
Object.defineProperty(exports, "isDate", { enumerable: true, get: function () { return neo4j_driver_core_1.isDate; } }); | ||
Object.defineProperty(exports, "isDateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isDateTime; } }); | ||
Object.defineProperty(exports, "isDuration", { enumerable: true, get: function () { return neo4j_driver_core_1.isDuration; } }); | ||
Object.defineProperty(exports, "isLocalDateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isLocalDateTime; } }); | ||
Object.defineProperty(exports, "isLocalTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isLocalTime; } }); | ||
Object.defineProperty(exports, "isNode", { enumerable: true, get: function () { return neo4j_driver_core_1.isNode; } }); | ||
Object.defineProperty(exports, "isPath", { enumerable: true, get: function () { return neo4j_driver_core_1.isPath; } }); | ||
Object.defineProperty(exports, "isPathSegment", { enumerable: true, get: function () { return neo4j_driver_core_1.isPathSegment; } }); | ||
Object.defineProperty(exports, "isRelationship", { enumerable: true, get: function () { return neo4j_driver_core_1.isRelationship; } }); | ||
Object.defineProperty(exports, "isTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isTime; } }); | ||
Object.defineProperty(exports, "isUnboundRelationship", { enumerable: true, get: function () { return neo4j_driver_core_1.isUnboundRelationship; } }); | ||
Object.defineProperty(exports, "LocalDateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.LocalDateTime; } }); | ||
Object.defineProperty(exports, "LocalTime", { enumerable: true, get: function () { return neo4j_driver_core_1.LocalTime; } }); | ||
Object.defineProperty(exports, "Time", { enumerable: true, get: function () { return neo4j_driver_core_1.Time; } }); | ||
Object.defineProperty(exports, "Node", { enumerable: true, get: function () { return neo4j_driver_core_1.Node; } }); | ||
Object.defineProperty(exports, "Path", { enumerable: true, get: function () { return neo4j_driver_core_1.Path; } }); | ||
Object.defineProperty(exports, "PathSegment", { enumerable: true, get: function () { return neo4j_driver_core_1.PathSegment; } }); | ||
Object.defineProperty(exports, "Relationship", { enumerable: true, get: function () { return neo4j_driver_core_1.Relationship; } }); | ||
Object.defineProperty(exports, "UnboundRelationship", { enumerable: true, get: function () { return neo4j_driver_core_1.UnboundRelationship; } }); | ||
Object.defineProperty(exports, "Record", { enumerable: true, get: function () { return neo4j_driver_core_1.Record; } }); | ||
Object.defineProperty(exports, "ResultSummary", { enumerable: true, get: function () { return neo4j_driver_core_1.ResultSummary; } }); | ||
Object.defineProperty(exports, "Plan", { enumerable: true, get: function () { return neo4j_driver_core_1.Plan; } }); | ||
Object.defineProperty(exports, "ProfiledPlan", { enumerable: true, get: function () { return neo4j_driver_core_1.ProfiledPlan; } }); | ||
Object.defineProperty(exports, "QueryStatistics", { enumerable: true, get: function () { return neo4j_driver_core_1.QueryStatistics; } }); | ||
Object.defineProperty(exports, "Notification", { enumerable: true, get: function () { return neo4j_driver_core_1.Notification; } }); | ||
Object.defineProperty(exports, "ServerInfo", { enumerable: true, get: function () { return neo4j_driver_core_1.ServerInfo; } }); | ||
Object.defineProperty(exports, "Result", { enumerable: true, get: function () { return neo4j_driver_core_1.Result; } }); | ||
Object.defineProperty(exports, "auth", { enumerable: true, get: function () { return neo4j_driver_core_1.auth; } }); | ||
Object.defineProperty(exports, "Session", { enumerable: true, get: function () { return neo4j_driver_core_1.Session; } }); | ||
Object.defineProperty(exports, "Transaction", { enumerable: true, get: function () { return neo4j_driver_core_1.Transaction; } }); | ||
Object.defineProperty(exports, "ManagedTransaction", { enumerable: true, get: function () { return neo4j_driver_core_1.ManagedTransaction; } }); | ||
Object.defineProperty(exports, "bookmarkManager", { enumerable: true, get: function () { return neo4j_driver_core_1.bookmarkManager; } }); | ||
var neo4j_driver_bolt_connection_1 = require("neo4j-driver-bolt-connection"); | ||
var session_rx_1 = __importDefault(require("./session-rx")); | ||
exports.RxSession = session_rx_1.default; | ||
var transaction_rx_1 = __importDefault(require("./transaction-rx")); | ||
exports.RxTransaction = transaction_rx_1.default; | ||
var transaction_managed_rx_1 = __importDefault(require("./transaction-managed-rx")); | ||
exports.RxManagedTransaction = transaction_managed_rx_1.default; | ||
var result_rx_1 = __importDefault(require("./result-rx")); | ||
exports.RxResult = result_rx_1.default; | ||
var _a = neo4j_driver_core_1.internal.util, ENCRYPTION_ON = _a.ENCRYPTION_ON, assertString = _a.assertString, isEmptyObjectOrNull = _a.isEmptyObjectOrNull, ServerAddress = neo4j_driver_core_1.internal.serverAddress.ServerAddress, urlUtil = neo4j_driver_core_1.internal.urlUtil; | ||
/** | ||
* @property {function(username: string, password: string, realm: ?string)} basic the function to create a | ||
* basic authentication token. | ||
* @property {function(base64EncodedTicket: string)} kerberos the function to create a Kerberos authentication token. | ||
* Accepts a single string argument - base64 encoded Kerberos ticket. | ||
* @property {function(principal: string, credentials: string, realm: string, scheme: string, parameters: ?object)} custom | ||
* the function to create a custom authentication token. | ||
* Construct a new Neo4j Driver. This is your main entry point for this | ||
* library. | ||
* | ||
* ## Configuration | ||
* | ||
* This function optionally takes a configuration argument. Available configuration | ||
* options are as follows: | ||
* | ||
* { | ||
* // Encryption level: ENCRYPTION_ON or ENCRYPTION_OFF. | ||
* encrypted: ENCRYPTION_ON|ENCRYPTION_OFF | ||
* | ||
* // Trust strategy to use if encryption is enabled. There is no mode to disable | ||
* // trust other than disabling encryption altogether. The reason for | ||
* // this is that if you don't know who you are talking to, it is easy for an | ||
* // attacker to hijack your encrypted connection, rendering encryption pointless. | ||
* // | ||
* // TRUST_SYSTEM_CA_SIGNED_CERTIFICATES is the default choice. For NodeJS environments, this | ||
* // means that you trust whatever certificates are in the default trusted certificate | ||
* // store of the underlying system. For Browser environments, the trusted certificate | ||
* // store is usually managed by the browser. Refer to your system or browser documentation | ||
* // if you want to explicitly add a certificate as trusted. | ||
* // | ||
* // TRUST_CUSTOM_CA_SIGNED_CERTIFICATES is another option for trust verification - | ||
* // whenever we establish an encrypted connection, we ensure the host is using | ||
* // an encryption certificate that is in, or is signed by, a certificate given | ||
* // as trusted through configuration. This option is only available for NodeJS environments. | ||
* // | ||
* // TRUST_ALL_CERTIFICATES means that you trust everything without any verifications | ||
* // steps carried out. This option is only available for NodeJS environments and should not | ||
* // be used on production systems. | ||
* trust: "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES" | "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES" | | ||
* "TRUST_ALL_CERTIFICATES", | ||
* | ||
* // List of one or more paths to trusted encryption certificates. This only | ||
* // works in the NodeJS bundle, and only matters if you use "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES". | ||
* // The certificate files should be in regular X.509 PEM format. | ||
* // For instance, ['./trusted.pem'] | ||
* trustedCertificates: [], | ||
* | ||
* // The maximum total number of connections allowed to be managed by the connection pool, per host. | ||
* // This includes both in-use and idle connections. No maximum connection pool size is imposed | ||
* // by default. | ||
* maxConnectionPoolSize: 100, | ||
* | ||
* // The maximum allowed lifetime for a pooled connection in milliseconds. Pooled connections older than this | ||
* // threshold will be closed and removed from the pool. Such discarding happens during connection acquisition | ||
* // so that new session is never backed by an old connection. Setting this option to a low value will cause | ||
* // a high connection churn and might result in a performance hit. It is recommended to set maximum lifetime | ||
* // to a slightly smaller value than the one configured in network equipment (load balancer, proxy, firewall, | ||
* // etc. can also limit maximum connection lifetime). No maximum lifetime limit is imposed by default. Zero | ||
* // and negative values result in lifetime not being checked. | ||
* maxConnectionLifetime: 60 * 60 * 1000, // 1 hour | ||
* | ||
* // The maximum amount of time to wait to acquire a connection from the pool (to either create a new | ||
* // connection or borrow an existing one. | ||
* connectionAcquisitionTimeout: 60000, // 1 minute | ||
* | ||
* // Specify the maximum time in milliseconds transactions are allowed to retry via | ||
* // `Session#executeRead()` and `Session#executeWrite()` functions. | ||
* // These functions will retry the given unit of work on `ServiceUnavailable`, `SessionExpired` and transient | ||
* // errors with exponential backoff using initial delay of 1 second. | ||
* // Default value is 30000 which is 30 seconds. | ||
* maxTransactionRetryTime: 30000, // 30 seconds | ||
* | ||
* // Specify socket connection timeout in milliseconds. Numeric values are expected. Negative and zero values | ||
* // result in no timeout being applied. Connection establishment will be then bound by the timeout configured | ||
* // on the operating system level. Default value is 30000, which is 30 seconds. | ||
* connectionTimeout: 30000, // 30 seconds | ||
* | ||
* // Make this driver always return native JavaScript numbers for integer values, instead of the | ||
* // dedicated {@link Integer} class. Values that do not fit in native number bit range will be represented as | ||
* // `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`. | ||
* // **Warning:** ResultSummary It is not always safe to enable this setting when JavaScript applications are not the only ones | ||
* // interacting with the database. Stored numbers might in such case be not representable by native | ||
* // {@link Number} type and thus driver will return lossy values. This might also happen when data was | ||
* // initially imported using neo4j import tool and contained numbers larger than | ||
* // `Number.MAX_SAFE_INTEGER`. Driver will then return positive infinity, which is lossy. | ||
* // Default value for this option is `false` because native JavaScript numbers might result | ||
* // in loss of precision in the general case. | ||
* disableLosslessIntegers: false, | ||
* | ||
* // Make this driver always return native Javascript {@link BigInt} for integer values, instead of the dedicated {@link Integer} class or {@link Number}. | ||
* // | ||
* // Default value for this option is `false` for backwards compatibility. | ||
* // | ||
* // **Warning:** `BigInt` doesn't implement the method `toJSON`. In maner of serialize it as `json`, It's needed to add a custom implementation of the `toJSON` on the | ||
* // `BigInt.prototype` {@see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#use_within_json} | ||
* useBigInt: false, | ||
* | ||
* // Specify the logging configuration for the driver. Object should have two properties `level` and `logger`. | ||
* // | ||
* // Property `level` represents the logging level which should be one of: 'error', 'warn', 'info' or 'debug'. This property is optional and | ||
* // its default value is 'info'. Levels have priorities: 'error': 0, 'warn': 1, 'info': 2, 'debug': 3. Enabling a certain level also enables all | ||
* // levels with lower priority. For example: 'error', 'warn' and 'info' will be logged when 'info' level is configured. | ||
* // | ||
* // Property `logger` represents the logging function which will be invoked for every log call with an acceptable level. The function should | ||
* // take two string arguments `level` and `message`. The function should not execute any blocking or long-running operations | ||
* // because it is often executed on a hot path. | ||
* // | ||
* // No logging is done by default. See `neo4j.logging` object that contains predefined logging implementations. | ||
* logging: { | ||
* level: 'info', | ||
* logger: (level, message) => console.log(level + ' ' + message) | ||
* }, | ||
* | ||
* // Specify a custom server address resolver function used by the routing driver to resolve the initial address used to create the driver. | ||
* // Such resolution happens: | ||
* // * during the very first rediscovery when driver is created | ||
* // * when all the known routers from the current routing table have failed and driver needs to fallback to the initial address | ||
* // | ||
* // In NodeJS environment driver defaults to performing a DNS resolution of the initial address using 'dns' module. | ||
* // In browser environment driver uses the initial address as-is. | ||
* // Value should be a function that takes a single string argument - the initial address. It should return an array of new addresses. | ||
* // Address is a string of shape '<host>:<port>'. Provided function can return either a Promise resolved with an array of addresses | ||
* // or array of addresses directly. | ||
* resolver: function(address) { | ||
* return ['127.0.0.1:8888', 'fallback.db.com:7687']; | ||
* }, | ||
* | ||
* // Optionally override the default user agent name. | ||
* userAgent: USER_AGENT | ||
* } | ||
* | ||
* @param {string} url The URL for the Neo4j database, for instance "neo4j://localhost" and/or "bolt://localhost" | ||
* @param {Map<string,string>} authToken Authentication credentials. See {@link auth} for helpers. | ||
* @param {Object} config Configuration object. See the configuration section above for details. | ||
* @returns {Driver} | ||
*/ | ||
var auth = { | ||
basic: function basic(username, password) { | ||
var realm = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; | ||
if (realm) { | ||
return { | ||
scheme: 'basic', | ||
principal: username, | ||
credentials: password, | ||
realm: realm | ||
}; | ||
} else { | ||
return { | ||
scheme: 'basic', | ||
principal: username, | ||
credentials: password | ||
}; | ||
function driver(url, authToken, config) { | ||
if (config === void 0) { config = {}; } | ||
assertString(url, 'Bolt URL'); | ||
var parsedUrl = urlUtil.parseDatabaseUrl(url); | ||
// Determine entryption/trust options from the URL. | ||
var routing = false; | ||
var encrypted = false; | ||
var trust; | ||
switch (parsedUrl.scheme) { | ||
case 'bolt': | ||
break; | ||
case 'bolt+s': | ||
encrypted = true; | ||
trust = 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'; | ||
break; | ||
case 'bolt+ssc': | ||
encrypted = true; | ||
trust = 'TRUST_ALL_CERTIFICATES'; | ||
break; | ||
case 'neo4j': | ||
routing = true; | ||
break; | ||
case 'neo4j+s': | ||
encrypted = true; | ||
trust = 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'; | ||
routing = true; | ||
break; | ||
case 'neo4j+ssc': | ||
encrypted = true; | ||
trust = 'TRUST_ALL_CERTIFICATES'; | ||
routing = true; | ||
break; | ||
default: | ||
throw new Error("Unknown scheme: ".concat(parsedUrl.scheme)); | ||
} | ||
}, | ||
kerberos: function kerberos(base64EncodedTicket) { | ||
return { | ||
scheme: 'kerberos', | ||
principal: '', | ||
// This empty string is required for backwards compatibility. | ||
credentials: base64EncodedTicket | ||
// Encryption enabled on URL, propagate trust to the config. | ||
if (encrypted) { | ||
// Check for configuration conflict between URL and config. | ||
if ('encrypted' in config || 'trust' in config) { | ||
throw new Error('Encryption/trust can only be configured either through URL or config, not both'); | ||
} | ||
config.encrypted = ENCRYPTION_ON; | ||
config.trust = trust; | ||
} | ||
// Sanitize authority token. Nicer error from server when a scheme is set. | ||
authToken = authToken || {}; | ||
authToken.scheme = authToken.scheme || 'none'; | ||
// Use default user agent or user agent specified by user. | ||
config.userAgent = config.userAgent || USER_AGENT; | ||
var address = ServerAddress.fromUrl(parsedUrl.hostAndPort); | ||
var meta = { | ||
address: address, | ||
typename: routing ? 'Routing' : 'Direct', | ||
routing: routing | ||
}; | ||
}, | ||
custom: function custom(principal, credentials, realm, scheme) { | ||
var parameters = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined; | ||
if (parameters) { | ||
return { | ||
scheme: scheme, | ||
principal: principal, | ||
credentials: credentials, | ||
realm: realm, | ||
parameters: parameters | ||
}; | ||
} else { | ||
return { | ||
scheme: scheme, | ||
principal: principal, | ||
credentials: credentials, | ||
realm: realm | ||
}; | ||
return new driver_1.Driver(meta, config, createConnectionProviderFunction()); | ||
function createConnectionProviderFunction() { | ||
if (routing) { | ||
return function (id, config, log, hostNameResolver) { | ||
return new neo4j_driver_bolt_connection_1.RoutingConnectionProvider({ | ||
id: id, | ||
config: config, | ||
log: log, | ||
hostNameResolver: hostNameResolver, | ||
authToken: authToken, | ||
address: address, | ||
userAgent: config.userAgent, | ||
routingContext: parsedUrl.query | ||
}); | ||
}; | ||
} | ||
else { | ||
if (!isEmptyObjectOrNull(parsedUrl.query)) { | ||
throw new Error("Parameters are not supported with none routed scheme. Given URL: '".concat(url, "'")); | ||
} | ||
return function (id, config, log) { | ||
return new neo4j_driver_bolt_connection_1.DirectConnectionProvider({ | ||
id: id, | ||
config: config, | ||
log: log, | ||
authToken: authToken, | ||
address: address, | ||
userAgent: config.userAgent | ||
}); | ||
}; | ||
} | ||
} | ||
} | ||
}; | ||
exports.auth = auth; | ||
var USER_AGENT = 'neo4j-javascript/' + _version["default"]; | ||
} | ||
exports.driver = driver; | ||
/** | ||
* Verifies if the driver can reach a server at the given url. | ||
* | ||
* @experimental | ||
* @since 5.0.0 | ||
* @param {string} url The URL for the Neo4j database, for instance "neo4j://localhost" and/or "bolt://localhost" | ||
* @param {object} config Configuration object. See the {@link driver} | ||
* @returns {true} When the server is reachable | ||
* @throws {Error} When the server is not reachable or the url is invalid | ||
*/ | ||
function hasReachableServer(url, config) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var nonLoggedDriver; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
nonLoggedDriver = driver(url, { scheme: 'none', principal: '', credentials: '' }, config); | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, , 3, 5]); | ||
return [4 /*yield*/, nonLoggedDriver.getNegotiatedProtocolVersion()]; | ||
case 2: | ||
_a.sent(); | ||
return [2 /*return*/, true]; | ||
case 3: return [4 /*yield*/, nonLoggedDriver.close()]; | ||
case 4: | ||
_a.sent(); | ||
return [7 /*endfinally*/]; | ||
case 5: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
} | ||
exports.hasReachableServer = hasReachableServer; | ||
var USER_AGENT = 'neo4j-javascript/' + version_1.default; | ||
/** | ||
* Object containing predefined logging configurations. These are expected to be used as values of the driver config's `logging` property. | ||
@@ -184,260 +379,144 @@ * @property {function(level: ?string): object} console the function to create a logging config that prints all messages to `console.log` with | ||
*/ | ||
var logging = { | ||
console: function (_console) { | ||
function console(_x) { | ||
return _console.apply(this, arguments); | ||
console: function (level) { | ||
return { | ||
level: level, | ||
logger: function (level, message) { | ||
return console.log("".concat(global.Date.now(), " ").concat(level.toUpperCase(), " ").concat(message)); | ||
} | ||
}; | ||
} | ||
console.toString = function () { | ||
return _console.toString(); | ||
}; | ||
return console; | ||
}(function (level) { | ||
return { | ||
level: level, | ||
logger: function logger(level, message) { | ||
return console.log("".concat(global.Date.now(), " ").concat(level.toUpperCase(), " ").concat(message)); | ||
} | ||
}; | ||
}) | ||
/** | ||
* Construct a new Neo4j Driver. This is your main entry point for this | ||
* library. | ||
* | ||
* ## Configuration | ||
* | ||
* This function optionally takes a configuration argument. Available configuration | ||
* options are as follows: | ||
* | ||
* { | ||
* // Encryption level: ENCRYPTION_ON or ENCRYPTION_OFF. | ||
* encrypted: ENCRYPTION_ON|ENCRYPTION_OFF | ||
* | ||
* // Trust strategy to use if encryption is enabled. There is no mode to disable | ||
* // trust other than disabling encryption altogether. The reason for | ||
* // this is that if you don't know who you are talking to, it is easy for an | ||
* // attacker to hijack your encrypted connection, rendering encryption pointless. | ||
* // | ||
* // TRUST_ALL_CERTIFICATES is the default choice for NodeJS deployments. It only requires | ||
* // new host to provide a certificate and does no verification of the provided certificate. | ||
* // | ||
* // TRUST_CUSTOM_CA_SIGNED_CERTIFICATES is the classic approach to trust verification - | ||
* // whenever we establish an encrypted connection, we ensure the host is using | ||
* // an encryption certificate that is in, or is signed by, a certificate listed | ||
* // as trusted. In the web bundle, this list of trusted certificates is maintained | ||
* // by the web browser. In NodeJS, you configure the list with the next config option. | ||
* // | ||
* // TRUST_SYSTEM_CA_SIGNED_CERTIFICATES means that you trust whatever certificates | ||
* // are in the default certificate chain of the underlying system. | ||
* trust: "TRUST_ALL_CERTIFICATES" | "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES" | | ||
* "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES", | ||
* | ||
* // List of one or more paths to trusted encryption certificates. This only | ||
* // works in the NodeJS bundle, and only matters if you use "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES". | ||
* // The certificate files should be in regular X.509 PEM format. | ||
* // For instance, ['./trusted.pem'] | ||
* trustedCertificates: [], | ||
* | ||
* // The maximum total number of connections allowed to be managed by the connection pool, per host. | ||
* // This includes both in-use and idle connections. No maximum connection pool size is imposed | ||
* // by default. | ||
* maxConnectionPoolSize: 100, | ||
* | ||
* // The maximum allowed lifetime for a pooled connection in milliseconds. Pooled connections older than this | ||
* // threshold will be closed and removed from the pool. Such discarding happens during connection acquisition | ||
* // so that new session is never backed by an old connection. Setting this option to a low value will cause | ||
* // a high connection churn and might result in a performance hit. It is recommended to set maximum lifetime | ||
* // to a slightly smaller value than the one configured in network equipment (load balancer, proxy, firewall, | ||
* // etc. can also limit maximum connection lifetime). No maximum lifetime limit is imposed by default. Zero | ||
* // and negative values result in lifetime not being checked. | ||
* maxConnectionLifetime: 60 * 60 * 1000, // 1 hour | ||
* | ||
* // The maximum amount of time to wait to acquire a connection from the pool (to either create a new | ||
* // connection or borrow an existing one. | ||
* connectionAcquisitionTimeout: 60000, // 1 minute | ||
* | ||
* // Specify the maximum time in milliseconds transactions are allowed to retry via | ||
* // `Session#readTransaction()` and `Session#writeTransaction()` functions. | ||
* // These functions will retry the given unit of work on `ServiceUnavailable`, `SessionExpired` and transient | ||
* // errors with exponential backoff using initial delay of 1 second. | ||
* // Default value is 30000 which is 30 seconds. | ||
* maxTransactionRetryTime: 30000, // 30 seconds | ||
* | ||
* // Specify socket connection timeout in milliseconds. Numeric values are expected. Negative and zero values | ||
* // result in no timeout being applied. Connection establishment will be then bound by the timeout configured | ||
* // on the operating system level. Default value is 5000, which is 5 seconds. | ||
* connectionTimeout: 5000, // 5 seconds | ||
* | ||
* // Make this driver always return native JavaScript numbers for integer values, instead of the | ||
* // dedicated {@link Integer} class. Values that do not fit in native number bit range will be represented as | ||
* // `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`. | ||
* // **Warning:** ResultSummary It is not always safe to enable this setting when JavaScript applications are not the only ones | ||
* // interacting with the database. Stored numbers might in such case be not representable by native | ||
* // {@link Number} type and thus driver will return lossy values. This might also happen when data was | ||
* // initially imported using neo4j import tool and contained numbers larger than | ||
* // `Number.MAX_SAFE_INTEGER`. Driver will then return positive infinity, which is lossy. | ||
* // Default value for this option is `false` because native JavaScript numbers might result | ||
* // in loss of precision in the general case. | ||
* disableLosslessIntegers: false, | ||
* | ||
* // Specify the logging configuration for the driver. Object should have two properties `level` and `logger`. | ||
* // | ||
* // Property `level` represents the logging level which should be one of: 'error', 'warn', 'info' or 'debug'. This property is optional and | ||
* // its default value is 'info'. Levels have priorities: 'error': 0, 'warn': 1, 'info': 2, 'debug': 3. Enabling a certain level also enables all | ||
* // levels with lower priority. For example: 'error', 'warn' and 'info' will be logged when 'info' level is configured. | ||
* // | ||
* // Property `logger` represents the logging function which will be invoked for every log call with an acceptable level. The function should | ||
* // take two string arguments `level` and `message`. The function should not execute any blocking or long-running operations | ||
* // because it is often executed on a hot path. | ||
* // | ||
* // No logging is done by default. See `neo4j.logging` object that contains predefined logging implementations. | ||
* logging: { | ||
* level: 'info', | ||
* logger: (level, message) => console.log(level + ' ' + message) | ||
* }, | ||
* | ||
* // Specify a custom server address resolver function used by the routing driver to resolve the initial address used to create the driver. | ||
* // Such resolution happens: | ||
* // * during the very first rediscovery when driver is created | ||
* // * when all the known routers from the current routing table have failed and driver needs to fallback to the initial address | ||
* // | ||
* // In NodeJS environment driver defaults to performing a DNS resolution of the initial address using 'dns' module. | ||
* // In browser environment driver uses the initial address as-is. | ||
* // Value should be a function that takes a single string argument - the initial address. It should return an array of new addresses. | ||
* // Address is a string of shape '<host>:<port>'. Provided function can return either a Promise resolved with an array of addresses | ||
* // or array of addresses directly. | ||
* resolver: function(address) { | ||
* return ['127.0.0.1:8888', 'fallback.db.com:7687']; | ||
* }, | ||
* } | ||
* | ||
* @param {string} url The URL for the Neo4j database, for instance "bolt://localhost" | ||
* @param {Map<String,String>} authToken Authentication credentials. See {@link auth} for helpers. | ||
* @param {Object} config Configuration object. See the configuration section above for details. | ||
* @returns {Driver} | ||
*/ | ||
}; | ||
exports.logging = logging; | ||
function driver(url, authToken) { | ||
var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
(0, _util.assertString)(url, 'Bolt URL'); | ||
var parsedUrl = _urlUtil["default"].parseDatabaseUrl(url); | ||
if (parsedUrl.scheme === 'neo4j') { | ||
return new _routingDriver["default"](_serverAddress["default"].fromUrl(parsedUrl.hostAndPort), parsedUrl.query, USER_AGENT, authToken, config); | ||
} else if (parsedUrl.scheme === 'bolt') { | ||
if (!(0, _util.isEmptyObjectOrNull)(parsedUrl.query)) { | ||
throw new Error("Parameters are not supported with scheme 'bolt'. Given URL: '".concat(url, "'")); | ||
} | ||
return new _driver.Driver(_serverAddress["default"].fromUrl(parsedUrl.hostAndPort), USER_AGENT, authToken, config); | ||
} else { | ||
throw new Error("Unknown scheme: ".concat(parsedUrl.scheme)); | ||
} | ||
} | ||
/** | ||
* Object containing constructors for all neo4j types. | ||
*/ | ||
var types = { | ||
Node: _graphTypes.Node, | ||
Relationship: _graphTypes.Relationship, | ||
UnboundRelationship: _graphTypes.UnboundRelationship, | ||
PathSegment: _graphTypes.PathSegment, | ||
Path: _graphTypes.Path, | ||
Result: _result["default"], | ||
ResultSummary: _resultSummary["default"], | ||
Record: _record["default"], | ||
Point: _spatialTypes.Point, | ||
Date: _temporalTypes.Date, | ||
DateTime: _temporalTypes.DateTime, | ||
Duration: _temporalTypes.Duration, | ||
LocalDateTime: _temporalTypes.LocalDateTime, | ||
LocalTime: _temporalTypes.LocalTime, | ||
Time: _temporalTypes.Time, | ||
Integer: _integer["default"] | ||
/** | ||
* Object containing string constants representing session access modes. | ||
*/ | ||
Node: neo4j_driver_core_1.Node, | ||
Relationship: neo4j_driver_core_1.Relationship, | ||
UnboundRelationship: neo4j_driver_core_1.UnboundRelationship, | ||
PathSegment: neo4j_driver_core_1.PathSegment, | ||
Path: neo4j_driver_core_1.Path, | ||
Result: neo4j_driver_core_1.Result, | ||
ResultSummary: neo4j_driver_core_1.ResultSummary, | ||
Record: neo4j_driver_core_1.Record, | ||
Point: neo4j_driver_core_1.Point, | ||
Date: neo4j_driver_core_1.Date, | ||
DateTime: neo4j_driver_core_1.DateTime, | ||
Duration: neo4j_driver_core_1.Duration, | ||
LocalDateTime: neo4j_driver_core_1.LocalDateTime, | ||
LocalTime: neo4j_driver_core_1.LocalTime, | ||
Time: neo4j_driver_core_1.Time, | ||
Integer: neo4j_driver_core_1.Integer | ||
}; | ||
exports.types = types; | ||
/** | ||
* Object containing string constants representing session access modes. | ||
*/ | ||
var session = { | ||
READ: _driver.READ, | ||
WRITE: _driver.WRITE | ||
/** | ||
* Object containing string constants representing predefined {@link Neo4jError} codes. | ||
*/ | ||
READ: driver_1.READ, | ||
WRITE: driver_1.WRITE | ||
}; | ||
exports.session = session; | ||
var error = { | ||
SERVICE_UNAVAILABLE: _error.SERVICE_UNAVAILABLE, | ||
SESSION_EXPIRED: _error.SESSION_EXPIRED, | ||
PROTOCOL_ERROR: _error.PROTOCOL_ERROR | ||
/** | ||
* Object containing functions to work with {@link Integer} objects. | ||
*/ | ||
}; | ||
exports.error = error; | ||
/** | ||
* Object containing functions to work with {@link Integer} objects. | ||
*/ | ||
var integer = { | ||
toNumber: _integer.toNumber, | ||
toString: _integer.toString, | ||
inSafeRange: _integer.inSafeRange | ||
/** | ||
* Object containing functions to work with spatial types, like {@link Point}. | ||
*/ | ||
toNumber: neo4j_driver_core_1.toNumber, | ||
toString: neo4j_driver_core_1.toString, | ||
inSafeRange: neo4j_driver_core_1.inSafeRange | ||
}; | ||
exports.integer = integer; | ||
/** | ||
* Object containing functions to work with spatial types, like {@link Point}. | ||
*/ | ||
var spatial = { | ||
isPoint: _spatialTypes.isPoint | ||
/** | ||
* Object containing functions to work with temporal types, like {@link Time} or {@link Duration}. | ||
*/ | ||
isPoint: neo4j_driver_core_1.isPoint | ||
}; | ||
exports.spatial = spatial; | ||
/** | ||
* Object containing functions to work with temporal types, like {@link Time} or {@link Duration}. | ||
*/ | ||
var temporal = { | ||
isDuration: _temporalTypes.isDuration, | ||
isLocalTime: _temporalTypes.isLocalTime, | ||
isTime: _temporalTypes.isTime, | ||
isDate: _temporalTypes.isDate, | ||
isLocalDateTime: _temporalTypes.isLocalDateTime, | ||
isDateTime: _temporalTypes.isDateTime | ||
/** | ||
* @private | ||
*/ | ||
isDuration: neo4j_driver_core_1.isDuration, | ||
isLocalTime: neo4j_driver_core_1.isLocalTime, | ||
isTime: neo4j_driver_core_1.isTime, | ||
isDate: neo4j_driver_core_1.isDate, | ||
isLocalDateTime: neo4j_driver_core_1.isLocalDateTime, | ||
isDateTime: neo4j_driver_core_1.isDateTime | ||
}; | ||
exports.temporal = temporal; | ||
/** | ||
* Object containing functions to work with graph types, like {@link Node} or {@link Relationship}. | ||
*/ | ||
var graph = { | ||
isNode: neo4j_driver_core_1.isNode, | ||
isPath: neo4j_driver_core_1.isPath, | ||
isPathSegment: neo4j_driver_core_1.isPathSegment, | ||
isRelationship: neo4j_driver_core_1.isRelationship, | ||
isUnboundRelationship: neo4j_driver_core_1.isUnboundRelationship | ||
}; | ||
exports.graph = graph; | ||
/** | ||
* @private | ||
*/ | ||
var forExport = { | ||
driver: driver, | ||
"int": _integer["int"], | ||
isInt: _integer.isInt, | ||
isPoint: _spatialTypes.isPoint, | ||
isDuration: _temporalTypes.isDuration, | ||
isLocalTime: _temporalTypes.isLocalTime, | ||
isTime: _temporalTypes.isTime, | ||
isDate: _temporalTypes.isDate, | ||
isLocalDateTime: _temporalTypes.isLocalDateTime, | ||
isDateTime: _temporalTypes.isDateTime, | ||
integer: integer, | ||
Neo4jError: _error.Neo4jError, | ||
auth: auth, | ||
logging: logging, | ||
types: types, | ||
session: session, | ||
error: error, | ||
spatial: spatial, | ||
temporal: temporal | ||
driver: driver, | ||
hasReachableServer: hasReachableServer, | ||
int: neo4j_driver_core_1.int, | ||
isInt: neo4j_driver_core_1.isInt, | ||
isPoint: neo4j_driver_core_1.isPoint, | ||
isDuration: neo4j_driver_core_1.isDuration, | ||
isLocalTime: neo4j_driver_core_1.isLocalTime, | ||
isTime: neo4j_driver_core_1.isTime, | ||
isDate: neo4j_driver_core_1.isDate, | ||
isLocalDateTime: neo4j_driver_core_1.isLocalDateTime, | ||
isDateTime: neo4j_driver_core_1.isDateTime, | ||
isNode: neo4j_driver_core_1.isNode, | ||
isPath: neo4j_driver_core_1.isPath, | ||
isPathSegment: neo4j_driver_core_1.isPathSegment, | ||
isRelationship: neo4j_driver_core_1.isRelationship, | ||
isUnboundRelationship: neo4j_driver_core_1.isUnboundRelationship, | ||
integer: integer, | ||
Neo4jError: neo4j_driver_core_1.Neo4jError, | ||
isRetryableError: neo4j_driver_core_1.isRetryableError, | ||
auth: neo4j_driver_core_1.auth, | ||
logging: logging, | ||
types: types, | ||
session: session, | ||
error: neo4j_driver_core_1.error, | ||
graph: graph, | ||
spatial: spatial, | ||
temporal: temporal, | ||
Driver: driver_1.Driver, | ||
Session: neo4j_driver_core_1.Session, | ||
Transaction: neo4j_driver_core_1.Transaction, | ||
ManagedTransaction: neo4j_driver_core_1.ManagedTransaction, | ||
Result: neo4j_driver_core_1.Result, | ||
RxSession: session_rx_1.default, | ||
RxTransaction: transaction_rx_1.default, | ||
RxManagedTransaction: transaction_managed_rx_1.default, | ||
RxResult: result_rx_1.default, | ||
ResultSummary: neo4j_driver_core_1.ResultSummary, | ||
Plan: neo4j_driver_core_1.Plan, | ||
ProfiledPlan: neo4j_driver_core_1.ProfiledPlan, | ||
QueryStatistics: neo4j_driver_core_1.QueryStatistics, | ||
Notification: neo4j_driver_core_1.Notification, | ||
ServerInfo: neo4j_driver_core_1.ServerInfo, | ||
Record: neo4j_driver_core_1.Record, | ||
Node: neo4j_driver_core_1.Node, | ||
Relationship: neo4j_driver_core_1.Relationship, | ||
UnboundRelationship: neo4j_driver_core_1.UnboundRelationship, | ||
Path: neo4j_driver_core_1.Path, | ||
PathSegment: neo4j_driver_core_1.PathSegment, | ||
Point: neo4j_driver_core_1.Point, | ||
Integer: neo4j_driver_core_1.Integer, | ||
Duration: neo4j_driver_core_1.Duration, | ||
LocalTime: neo4j_driver_core_1.LocalTime, | ||
Time: neo4j_driver_core_1.Time, | ||
Date: neo4j_driver_core_1.Date, | ||
LocalDateTime: neo4j_driver_core_1.LocalDateTime, | ||
DateTime: neo4j_driver_core_1.DateTime, | ||
bookmarkManager: neo4j_driver_core_1.bookmarkManager | ||
}; | ||
var _default = forExport; | ||
exports["default"] = _default; | ||
exports.default = forExport; |
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.VERSION_IN_DEV = exports.VERSION_4_0_0 = exports.VERSION_3_5_0 = exports.VERSION_3_4_0 = exports.VERSION_3_2_0 = exports.ServerVersion = void 0; | ||
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); | ||
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); | ||
var _util = require("./util"); | ||
/** | ||
* Copyright (c) 2002-2019 "Neo4j," | ||
* Copyright (c) "Neo4j" | ||
* Neo4j Sweden AB [http://neo4j.com] | ||
@@ -34,33 +20,61 @@ * | ||
*/ | ||
var SERVER_VERSION_REGEX = new RegExp('^(Neo4j/)?(\\d+)\\.(\\d+)(?:\\.)?(\\d*)(\\.|-|\\+)?([0-9A-Za-z-.]*)?$'); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.VERSION_IN_DEV = exports.VERSION_4_0_0 = exports.VERSION_3_5_0 = exports.VERSION_3_4_0 = exports.VERSION_3_2_0 = exports.ServerVersion = void 0; | ||
var neo4j_driver_core_1 = require("neo4j-driver-core"); | ||
var assertString = neo4j_driver_core_1.internal.util.assertString; | ||
var SERVER_VERSION_REGEX = /^(Neo4j\/)?(\d+)\.(\d+)(?:\.)?(\d*)(\.|-|\+)?([0-9A-Za-z-.]*)?$/; | ||
var NEO4J_IN_DEV_VERSION_STRING = 'Neo4j/dev'; | ||
var ServerVersion = | ||
/*#__PURE__*/ | ||
function () { | ||
/** | ||
* @constructor | ||
* @param {number} major the major version number. | ||
* @param {number} minor the minor version number. | ||
* @param {number} patch the patch version number. | ||
* @param {string} the original version string | ||
*/ | ||
function ServerVersion(major, minor, patch, originalVersionString) { | ||
(0, _classCallCheck2["default"])(this, ServerVersion); | ||
this.major = major; | ||
this.minor = minor; | ||
this.patch = patch; | ||
this._originalVersionString = originalVersionString; | ||
} | ||
/** | ||
* Fetch server version using the given driver. | ||
* @param {Driver} driver the driver to use. | ||
* @return {Promise<ServerVersion>} promise resolved with a {@link ServerVersion} object or rejected with error. | ||
*/ | ||
(0, _createClass2["default"])(ServerVersion, [{ | ||
key: "compareTo", | ||
var ServerVersion = /** @class */ (function () { | ||
/** | ||
* @constructor | ||
* @param {number} major the major version number. | ||
* @param {number} minor the minor version number. | ||
* @param {number} patch the patch version number. | ||
* @param {string} [originalVersionString] the original version string | ||
*/ | ||
function ServerVersion(major, minor, patch, originalVersionString) { | ||
this.major = major; | ||
this.minor = minor; | ||
this.patch = patch; | ||
this._originalVersionString = originalVersionString; | ||
} | ||
/** | ||
* Fetch server version using the given driver. | ||
* @param {Driver} driver the driver to use. | ||
* @return {Promise<ServerVersion>} promise resolved with a {@link ServerVersion} object or rejected with error. | ||
*/ | ||
ServerVersion.fromDriver = function (driver) { | ||
var session = driver.session(); | ||
return session | ||
.run('RETURN 1') | ||
.then(function (result) { | ||
return session | ||
.close() | ||
.then(function () { return ServerVersion.fromString(result.summary.server.version); }); | ||
}); | ||
}; | ||
/** | ||
* Parse given string to a {@link ServerVersion} object. | ||
* @param {string} versionStr the string to parse. | ||
* @return {ServerVersion} version for the given string. | ||
* @throws Error if given string can't be parsed. | ||
*/ | ||
ServerVersion.fromString = function (versionStr) { | ||
if (!versionStr) { | ||
return new ServerVersion(3, 0, 0); | ||
} | ||
assertString(versionStr, 'Neo4j version string'); | ||
if (versionStr.toLowerCase() === NEO4J_IN_DEV_VERSION_STRING.toLowerCase()) { | ||
return VERSION_IN_DEV; | ||
} | ||
var version = versionStr.match(SERVER_VERSION_REGEX); | ||
if (!version) { | ||
throw new Error("Unparsable Neo4j version: ".concat(versionStr)); | ||
} | ||
var major = parseIntStrict(version[2]); | ||
var minor = parseIntStrict(version[3]); | ||
var patch = parseIntStrict(version[4] || 0); | ||
return new ServerVersion(major, minor, patch, versionStr); | ||
}; | ||
/** | ||
* Compare this version to the given one. | ||
@@ -72,84 +86,31 @@ * @param {ServerVersion} other the version to compare with. | ||
*/ | ||
value: function compareTo(other) { | ||
var result = compareInts(this.major, other.major); | ||
if (result === 0) { | ||
result = compareInts(this.minor, other.minor); | ||
ServerVersion.prototype.compareTo = function (other) { | ||
var result = compareInts(this.major, other.major); | ||
if (result === 0) { | ||
result = compareInts(this.patch, other.patch); | ||
result = compareInts(this.minor, other.minor); | ||
if (result === 0) { | ||
result = compareInts(this.patch, other.patch); | ||
} | ||
} | ||
} | ||
return result; | ||
} | ||
}, { | ||
key: "toString", | ||
value: function toString() { | ||
if (this._originalVersionString) { | ||
return this._originalVersionString; | ||
} | ||
return "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); | ||
} | ||
}], [{ | ||
key: "fromDriver", | ||
value: function fromDriver(driver) { | ||
var session = driver.session(); | ||
return session.run('RETURN 1').then(function (result) { | ||
session.close(); | ||
return ServerVersion.fromString(result.summary.server.version); | ||
}); | ||
} | ||
/** | ||
* Parse given string to a {@link ServerVersion} object. | ||
* @param {string} versionStr the string to parse. | ||
* @return {ServerVersion} version for the given string. | ||
* @throws Error if given string can't be parsed. | ||
*/ | ||
}, { | ||
key: "fromString", | ||
value: function fromString(versionStr) { | ||
if (!versionStr) { | ||
return new ServerVersion(3, 0, 0); | ||
} | ||
(0, _util.assertString)(versionStr, 'Neo4j version string'); | ||
if (versionStr.toLowerCase() === NEO4J_IN_DEV_VERSION_STRING.toLowerCase()) { | ||
return VERSION_IN_DEV; | ||
} | ||
var version = versionStr.match(SERVER_VERSION_REGEX); | ||
if (!version) { | ||
throw new Error("Unparsable Neo4j version: ".concat(versionStr)); | ||
} | ||
var major = parseIntStrict(version[2]); | ||
var minor = parseIntStrict(version[3]); | ||
var patch = parseIntStrict(version[4] || 0); | ||
return new ServerVersion(major, minor, patch, versionStr); | ||
} | ||
}]); | ||
return ServerVersion; | ||
}(); | ||
return result; | ||
}; | ||
ServerVersion.prototype.toString = function () { | ||
if (this._originalVersionString) { | ||
return this._originalVersionString; | ||
} | ||
return "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); | ||
}; | ||
return ServerVersion; | ||
}()); | ||
exports.ServerVersion = ServerVersion; | ||
function parseIntStrict(str, name) { | ||
var value = parseInt(str, 10); | ||
if (!value && value !== 0) { | ||
throw new Error("Unparsable number ".concat(name, ": '").concat(str, "'")); | ||
} | ||
return value; | ||
var value = parseInt(str, 10); | ||
if (!value && value !== 0) { | ||
throw new Error("Unparsable number ".concat(name, ": '").concat(str, "'")); | ||
} | ||
return value; | ||
} | ||
function compareInts(x, y) { | ||
return x < y ? -1 : x === y ? 0 : 1; | ||
return x < y ? -1 : x === y ? 0 : 1; | ||
} | ||
var VERSION_3_2_0 = ServerVersion.fromString('Neo4j/3.2.0'); | ||
@@ -156,0 +117,0 @@ exports.VERSION_3_2_0 = VERSION_3_2_0; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports["default"] = void 0; | ||
/** | ||
* Copyright (c) 2002-2019 "Neo4j," | ||
* Copyright (c) "Neo4j" | ||
* Neo4j Sweden AB [http://neo4j.com] | ||
@@ -26,10 +20,11 @@ * | ||
*/ | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
// DO NOT CHANGE THE VERSION BELOW HERE | ||
// This is set by the build system at release time, using | ||
// gulp set --version <releaseversion> | ||
// | ||
// gulp set --x <releaseversion> | ||
// | ||
// This is set up this way to keep the version in the code in | ||
// sync with the npm package version, and to allow the build | ||
// system to control version names at packaging time. | ||
var _default = '0.0.0-dev'; | ||
exports["default"] = _default; | ||
exports.default = '3.4.0-alpha01'; |
106
package.json
{ | ||
"name": "neo4j-driver", | ||
"version": "2.0.0-alpha03", | ||
"description": "Connect to Neo4j 3.0.0 and up from JavaScript", | ||
"version": "3.4.0-alpha01", | ||
"description": "Connect to Neo4j 3.5.0 and up from JavaScript", | ||
"author": "Neo4j", | ||
@@ -13,24 +13,18 @@ "license": "Apache-2.0", | ||
"lint": "eslint --fix --ext .js ./", | ||
"format": "prettier-eslint '**/*.js' '**/*.json' '**/*.md' '**/*.ts' '**/*.html' --write", | ||
"test": "gulp test", | ||
"test::unit": "gulp test-nodejs-unit && gulp run-ts-declaration-tests", | ||
"test::browser": "gulp test-browser", | ||
"test::integration": "gulp test-nodejs-integration", | ||
"test::stress": "gulp run-stress-tests-without-jasmine", | ||
"build": "gulp all", | ||
"start-neo4j": "gulp start-neo4j", | ||
"stop-neo4j": "gulp stop-neo4j", | ||
"run-stress-tests": "gulp run-stress-tests", | ||
"run-stress-tests": "gulp run-stress-tests-without-jasmine", | ||
"run-ts-declaration-tests": "gulp run-ts-declaration-tests", | ||
"docs": "esdoc -c esdoc.json", | ||
"versionRelease": "gulp set --version $VERSION && npm version $VERSION --no-git-tag-version", | ||
"browser": "gulp browser && gulp test-browser" | ||
"versionRelease": "gulp set --x $VERSION && npm version $VERSION --no-git-tag-version", | ||
"browser": "gulp browser && gulp test-browser", | ||
"prepare": "npm run build", | ||
"clean": "rm -fr node_modules lib build" | ||
}, | ||
"husky": { | ||
"hooks": { | ||
"pre-commit": "lint-staged" | ||
} | ||
}, | ||
"lint-staged": { | ||
"*.{js,json,ts,md,html}": [ | ||
"prettier-eslint --write", | ||
"git add" | ||
] | ||
}, | ||
"main": "lib/index.js", | ||
@@ -44,27 +38,17 @@ "browser": { | ||
"devDependencies": { | ||
"@babel/core": "^7.4.4", | ||
"@babel/plugin-transform-runtime": "^7.4.4", | ||
"@babel/preset-env": "^7.4.4", | ||
"@babel/register": "^7.4.4", | ||
"async": "^2.6.2", | ||
"babel-eslint": "^10.0.1", | ||
"babelify": "^10.0.0", | ||
"browserify": "^16.2.3", | ||
"browserify-transform-tools": "^1.7.0", | ||
"@babel/core": "^7.20.7", | ||
"@babel/plugin-transform-runtime": "^7.19.6", | ||
"@babel/register": "^7.18.9", | ||
"@rollup/plugin-commonjs": "^21.1.0", | ||
"@rollup/plugin-node-resolve": "^13.3.0", | ||
"@types/jasmine": "^4.3.1", | ||
"async": "^3.2.4", | ||
"esdoc": "^1.1.0", | ||
"esdoc-importpath-plugin": "^1.0.2", | ||
"esdoc-standard-plugin": "^1.0.0", | ||
"eslint": "^5.16.0", | ||
"eslint-config-standard": "^12.0.0", | ||
"eslint-plugin-import": "^2.17.2", | ||
"eslint-plugin-jasmine": "^2.10.1", | ||
"eslint-plugin-node": "^9.0.1", | ||
"eslint-plugin-promise": "^4.1.1", | ||
"eslint-plugin-standard": "^4.0.0", | ||
"fancy-log": "^1.3.3", | ||
"fs-extra": "^8.0.1", | ||
"fancy-log": "^2.0.0", | ||
"fs-extra": "^10.1.0", | ||
"gulp": "^4.0.2", | ||
"gulp-babel": "^8.0.0", | ||
"gulp-batch": "^1.0.5", | ||
"gulp-decompress": "^2.0.2", | ||
"gulp-decompress": "^3.0.0", | ||
"gulp-download": "^0.0.1", | ||
@@ -74,37 +58,33 @@ "gulp-file": "^0.4.0", | ||
"gulp-jasmine": "^4.0.0", | ||
"gulp-replace": "^1.0.0", | ||
"gulp-replace": "^1.1.4", | ||
"gulp-typescript": "^5.0.1", | ||
"gulp-uglify": "^3.0.2", | ||
"gulp-watch": "^5.0.1", | ||
"husky": "^2.3.0", | ||
"jasmine-spec-reporter": "^4.2.1", | ||
"karma": "^4.1.0", | ||
"karma-browserify": "^6.0.0", | ||
"karma-chrome-launcher": "^2.2.0", | ||
"jasmine-spec-reporter": "^7.0.0", | ||
"karma": "^6.4.1", | ||
"karma-chrome-launcher": "^3.1.1", | ||
"karma-edge-launcher": "^0.4.2", | ||
"karma-firefox-launcher": "^1.1.0", | ||
"karma-firefox-launcher": "^2.1.2", | ||
"karma-ie-launcher": "^1.0.0", | ||
"karma-jasmine": "^2.0.1", | ||
"karma-jasmine": "^4.0.2", | ||
"karma-source-map-support": "^1.4.0", | ||
"karma-spec-reporter": "^0.0.32", | ||
"lint-staged": "^8.1.6", | ||
"lodash": "^4.17.11", | ||
"lolex": "^4.0.1", | ||
"minimist": "^1.2.0", | ||
"mustache": "^3.0.1", | ||
"prettier-eslint": "^8.8.2", | ||
"prettier-eslint-cli": "^4.7.1", | ||
"run-sequence": "^2.2.1", | ||
"semver": "^6.0.0", | ||
"tmp": "0.1.0", | ||
"typescript": "^3.4.5", | ||
"karma-spec-reporter": "^0.0.36", | ||
"karma-typescript": "^5.5.3", | ||
"karma-typescript-es6-transform": "^5.5.3", | ||
"lolex": "^6.0.0", | ||
"minimist": "^1.2.7", | ||
"rollup": "^2.77.4-1", | ||
"rollup-plugin-polyfill-node": "^0.11.0", | ||
"semver": "^7.3.8", | ||
"tmp": "0.2.1", | ||
"typescript": "^4.9.4", | ||
"vinyl-buffer": "^1.0.1", | ||
"vinyl-source-stream": "^2.0.0", | ||
"webpack": "^4.31.0" | ||
"webpack": "^5.75.0" | ||
}, | ||
"dependencies": { | ||
"@babel/runtime": "^7.4.4", | ||
"text-encoding-utf-8": "^1.0.2", | ||
"uri-js": "^4.2.2" | ||
} | ||
"neo4j-driver-bolt-connection": "^3.4.0-alpha01", | ||
"neo4j-driver-core": "^3.4.0-alpha01", | ||
"rxjs": "^7.8.0" | ||
}, | ||
"gitHead": "b41b355eeb88c7db83a75f6917a3ba9782637e18" | ||
} |
539
README.md
# Neo4j Driver for JavaScript | ||
A database driver for Neo4j 3.0.0+. | ||
This is the official Neo4j driver for JavaScript. | ||
Starting with 5.0, the Neo4j Drivers will be moving to a monthly release cadence. A minor version will be released on the last Friday of each month so as to maintain versioning consistency with the core product (Neo4j DBMS) which has also moved to a monthly cadence. | ||
As a policy, patch versions will not be released except on rare occasions. Bug fixes and updates will go into the latest minor version and users should upgrade to that. Driver upgrades within a major version will never contain breaking API changes. | ||
See also: https://neo4j.com/developer/kb/neo4j-supported-versions/ | ||
Resources to get you started: | ||
- [Detailed docs](http://neo4j.com/docs/api/javascript-driver/current/). | ||
- [Sample small project using the driver](https://github.com/neo4j-examples/movies-javascript-bolt) | ||
- [Sample application using the driver](https://github.com/neo4j-examples/neo4j-movies-template) | ||
- [API Documentation](https://neo4j.com/docs/api/javascript-driver/current/) | ||
- [Neo4j Manual](https://neo4j.com/docs/) | ||
- [Neo4j Refcard](https://neo4j.com/docs/cypher-refcard/current/) | ||
## Include module in Node.js application | ||
## What's New in 5.x | ||
- [Changelog](https://github.com/neo4j/neo4j-javascript-driver/wiki/5.0-changelog) | ||
## Including the Driver | ||
### In Node.js application | ||
Stable channel: | ||
@@ -37,3 +47,3 @@ | ||
```javascript | ||
driver.close() | ||
driver.close() // returns a Promise | ||
``` | ||
@@ -43,3 +53,3 @@ | ||
## Include in web browser | ||
### In web browser | ||
@@ -64,13 +74,32 @@ We build a special browser version of the driver, which supports connecting to Neo4j over WebSockets. | ||
This will make a global `neo4j` object available, where you can access the driver API at `neo4j`\*: | ||
This will make a global `neo4j` object available, where you can create a driver instance with `neo4j.driver`: | ||
```javascript | ||
var driver = neo4j.driver( | ||
'bolt://localhost', | ||
neo4j.auth.basic('neo4j', 'neo4j') | ||
'neo4j://localhost', | ||
neo4j.auth.basic('neo4j', 'password') | ||
) | ||
``` | ||
\* Since 2.0, driver API is moved from `neo4j.v1` to `neo4j`. | ||
From `5.4.0`, this version is also exported as ECMA Script Module. | ||
It can be imported from a module using the following statements: | ||
```javascript | ||
// Direct reference | ||
import neo4j from 'lib/browser/neo4j-web.esm.min.js' | ||
// unpkg CDN non-minified , version X.Y.Z where X.Y.Z >= 5.4.0 | ||
import neo4j from 'https://unpkg.com/browse/neo4j-driver@X.Y.Z/lib/browser/neo4j-web.esm.js' | ||
// unpkg CDN minified for production use, version X.Y.Z where X.Y.Z >= 5.4.0 | ||
import neo4j from 'https://unpkg.com/browse/neo4j-driver@X.Y.Z/lib/browser/neo4j-web.esm.min.js' | ||
// jsDelivr CDN non-minified, version X.Y.Z where X.Y.Z >= 5.4.0 | ||
import neo4j from 'https://cdn.jsdelivr.net/npm/neo4j-driver@X.Y.Z/lib/browser/neo4j-web.esm.js' | ||
// jsDelivr CDN minified for production use, version X.Y.Z where X.Y.Z >= 5.4.0 | ||
import neo4j from 'https://cdn.jsdelivr.net/npm/neo4j-driver@X.Y.Z/lib/browser/neo4j-web.esm.min.js' | ||
``` | ||
It is not required to explicitly close the driver on a web page. Web browser should gracefully close all open | ||
@@ -81,3 +110,3 @@ WebSockets when the page is unloaded. However, driver instance should be explicitly closed when it's lifetime | ||
```javascript | ||
driver.close() | ||
driver.close() // returns a Promise | ||
``` | ||
@@ -87,10 +116,10 @@ | ||
Driver lifecycle: | ||
### Constructing a Driver | ||
```javascript | ||
// Create a driver instance, for the user neo4j with password neo4j. | ||
// Create a driver instance, for the user `neo4j` with password `password`. | ||
// It should be enough to have a single driver per database per application. | ||
var driver = neo4j.driver( | ||
'bolt://localhost', | ||
neo4j.auth.basic('neo4j', 'neo4j') | ||
'neo4j://localhost', | ||
neo4j.auth.basic('neo4j', 'password') | ||
) | ||
@@ -100,7 +129,9 @@ | ||
// This closes all used network connections. | ||
driver.close() | ||
await driver.close() | ||
``` | ||
Session API: | ||
### Acquiring a Session | ||
#### Regular Session | ||
```javascript | ||
@@ -110,56 +141,150 @@ // Create a session to run Cypher statements in. | ||
var session = driver.session() | ||
``` | ||
##### with a Default Access Mode of `READ` | ||
```javascript | ||
var session = driver.session({ defaultAccessMode: neo4j.session.READ }) | ||
``` | ||
##### with Bookmarks | ||
```javascript | ||
var session = driver.session({ | ||
bookmarks: [bookmark1FromPreviousSession, bookmark2FromPreviousSession] | ||
}) | ||
``` | ||
##### against a Database | ||
```javascript | ||
var session = driver.session({ | ||
database: 'foo', | ||
defaultAccessMode: neo4j.session.WRITE | ||
}) | ||
``` | ||
#### Reactive Session | ||
```javascript | ||
// Create a reactive session to run Cypher statements in. | ||
// Note: Always make sure to close sessions when you are done using them! | ||
var rxSession = driver.rxSession() | ||
``` | ||
##### with a Default Access Mode of `READ` | ||
```javascript | ||
var rxSession = driver.rxSession({ defaultAccessMode: neo4j.session.READ }) | ||
``` | ||
##### with Bookmarks | ||
```javascript | ||
var rxSession = driver.rxSession({ | ||
bookmarks: [bookmark1FromPreviousSession, bookmark2FromPreviousSession] | ||
}) | ||
``` | ||
##### against a Database | ||
```javascript | ||
var rxSession = driver.rxSession({ | ||
database: 'foo', | ||
defaultAccessMode: neo4j.session.WRITE | ||
}) | ||
``` | ||
### Executing Queries | ||
#### Consuming Records with Streaming API | ||
```javascript | ||
// Run a Cypher statement, reading the result in a streaming manner as records arrive: | ||
session | ||
.run('MERGE (alice:Person {name : {nameParam} }) RETURN alice.name AS name', { | ||
.run('MERGE (alice:Person {name : $nameParam}) RETURN alice.name AS name', { | ||
nameParam: 'Alice' | ||
}) | ||
.subscribe({ | ||
onNext: function(record) { | ||
onKeys: keys => { | ||
console.log(keys) | ||
}, | ||
onNext: record => { | ||
console.log(record.get('name')) | ||
}, | ||
onCompleted: function() { | ||
session.close() | ||
onCompleted: () => { | ||
session.close() // returns a Promise | ||
}, | ||
onError: function(error) { | ||
onError: error => { | ||
console.log(error) | ||
} | ||
}) | ||
``` | ||
// or | ||
Subscriber API allows following combinations of `onKeys`, `onNext`, `onCompleted` and `onError` callback invocations: | ||
- zero or one `onKeys`, | ||
- zero or more `onNext` followed by `onCompleted` when operation was successful. `onError` will not be invoked in this case | ||
- zero or more `onNext` followed by `onError` when operation failed. Callback `onError` might be invoked after couple `onNext` invocations because records are streamed lazily by the database. `onCompleted` will not be invoked in this case. | ||
#### Consuming Records with Promise API | ||
```javascript | ||
// the Promise way, where the complete result is collected before we act on it: | ||
session | ||
.run('MERGE (james:Person {name : {nameParam} }) RETURN james.name AS name', { | ||
.run('MERGE (james:Person {name : $nameParam}) RETURN james.name AS name', { | ||
nameParam: 'James' | ||
}) | ||
.then(function(result) { | ||
result.records.forEach(function(record) { | ||
.then(result => { | ||
result.records.forEach(record => { | ||
console.log(record.get('name')) | ||
}) | ||
session.close() | ||
}) | ||
.catch(function(error) { | ||
.catch(error => { | ||
console.log(error) | ||
}) | ||
.then(() => session.close()) | ||
``` | ||
Transaction functions API: | ||
#### Consuming Records with Reactive API | ||
```javascript | ||
rxSession | ||
.run('MERGE (james:Person {name: $nameParam}) RETURN james.name AS name', { | ||
nameParam: 'Bob' | ||
}) | ||
.records() | ||
.pipe( | ||
map(record => record.get('name')), | ||
concatWith(rxSession.close()) | ||
) | ||
.subscribe({ | ||
next: data => console.log(data), | ||
complete: () => console.log('completed'), | ||
error: err => console.log(err) | ||
}) | ||
``` | ||
### Transaction functions | ||
```javascript | ||
// Transaction functions provide a convenient API with minimal boilerplate and | ||
// retries on network fluctuations and transient errors. Maximum retry time is | ||
// configured on the driver level and is 30 seconds by default: | ||
neo4j.driver('bolt://localhost', neo4j.auth.basic('neo4j', 'neo4j'), { | ||
// Applies both to standard and reactive sessions. | ||
neo4j.driver('neo4j://localhost', neo4j.auth.basic('neo4j', 'password'), { | ||
maxTransactionRetryTime: 30000 | ||
}) | ||
``` | ||
#### Reading with Async Session | ||
```javascript | ||
// It is possible to execute read transactions that will benefit from automatic | ||
// retries on both single instance ('bolt' URI scheme) and Causal Cluster | ||
// ('neo4j' URI scheme) and will get automatic load balancing in cluster deployments | ||
var readTxResultPromise = session.readTransaction(function(transaction) { | ||
var readTxResultPromise = session.readTransaction(txc => { | ||
// used transaction will be committed automatically, no need for explicit commit/rollback | ||
var result = transaction.run( | ||
'MATCH (person:Person) RETURN person.name AS name' | ||
) | ||
var result = txc.run('MATCH (person:Person) RETURN person.name AS name') | ||
// at this point it is possible to either return the result or process it and return the | ||
@@ -172,23 +297,42 @@ // result of processing it is also possible to run more statements in the same transaction | ||
readTxResultPromise | ||
.then(function(result) { | ||
session.close() | ||
.then(result => { | ||
console.log(result.records) | ||
}) | ||
.catch(function(error) { | ||
.catch(error => { | ||
console.log(error) | ||
}) | ||
.then(() => session.close()) | ||
``` | ||
#### Reading with Reactive Session | ||
```javascript | ||
rxSession | ||
.readTransaction(txc => | ||
txc | ||
.run('MATCH (person:Person) RETURN person.name AS name') | ||
.records() | ||
.pipe(map(record => record.get('name'))) | ||
) | ||
.subscribe({ | ||
next: data => console.log(data), | ||
complete: () => console.log('completed'), | ||
error: err => console.log(error) | ||
}) | ||
``` | ||
#### Writing with Async Session | ||
```javascript | ||
// It is possible to execute write transactions that will benefit from automatic retries | ||
// on both single instance ('bolt' URI scheme) and Causal Cluster ('neo4j' URI scheme) | ||
var writeTxResultPromise = session.writeTransaction(function(transaction) { | ||
var writeTxResultPromise = session.writeTransaction(async txc => { | ||
// used transaction will be committed automatically, no need for explicit commit/rollback | ||
var result = transaction.run( | ||
"MERGE (alice:Person {name : 'Alice' }) RETURN alice.name AS name" | ||
var result = await txc.run( | ||
"MERGE (alice:Person {name : 'Alice'}) RETURN alice.name AS name" | ||
) | ||
// at this point it is possible to either return the result or process it and return the | ||
// result of processing it is also possible to run more statements in the same transaction | ||
return result.records.map(function(record) { | ||
return record.get('name') | ||
}) | ||
return result.records.map(record => record.get('name')) | ||
}) | ||
@@ -198,123 +342,120 @@ | ||
writeTxResultPromise | ||
.then(function(namesArray) { | ||
session.close() | ||
.then(namesArray => { | ||
console.log(namesArray) | ||
}) | ||
.catch(function(error) { | ||
.catch(error => { | ||
console.log(error) | ||
}) | ||
.then(() => session.close()) | ||
``` | ||
Explicit transactions API: | ||
#### Writing with Reactive Session | ||
```javascript | ||
// run statement in a transaction | ||
var tx = session.beginTransaction() | ||
rxSession | ||
.writeTransaction(txc => | ||
txc | ||
.run("MERGE (alice:Person {name: 'James'}) RETURN alice.name AS name") | ||
.records() | ||
.pipe(map(record => record.get('name'))) | ||
) | ||
.subscribe({ | ||
next: data => console.log(data), | ||
complete: () => console.log('completed'), | ||
error: error => console.log(error) | ||
}) | ||
``` | ||
tx.run('MERGE (bob:Person {name : {nameParam} }) RETURN bob.name AS name', { | ||
nameParam: 'Bob' | ||
}).subscribe({ | ||
onNext: function(record) { | ||
console.log(record.get('name')) | ||
}, | ||
onCompleted: function() { | ||
console.log('First query completed') | ||
}, | ||
onError: function(error) { | ||
console.log(error) | ||
} | ||
}) | ||
### Explicit Transactions | ||
tx.run('MERGE (adam:Person {name : {nameParam} }) RETURN adam.name AS name', { | ||
nameParam: 'Adam' | ||
}).subscribe({ | ||
onNext: function(record) { | ||
console.log(record.get('name')) | ||
}, | ||
onCompleted: function() { | ||
console.log('Second query completed') | ||
}, | ||
onError: function(error) { | ||
console.log(error) | ||
} | ||
}) | ||
#### With Async Session | ||
//decide if the transaction should be committed or rolled back | ||
var success = false | ||
```javascript | ||
// run statement in a transaction | ||
const txc = session.beginTransaction() | ||
try { | ||
const result1 = await txc.run( | ||
'MERGE (bob:Person {name: $nameParam}) RETURN bob.name AS name', | ||
{ | ||
nameParam: 'Bob' | ||
} | ||
) | ||
result1.records.forEach(r => console.log(r.get('name'))) | ||
console.log('First query completed') | ||
if (success) { | ||
tx.commit().subscribe({ | ||
onCompleted: function() { | ||
// this transaction is now committed and session can be closed | ||
session.close() | ||
}, | ||
onError: function(error) { | ||
console.log(error) | ||
const result2 = await txc.run( | ||
'MERGE (adam:Person {name: $nameParam}) RETURN adam.name AS name', | ||
{ | ||
nameParam: 'Adam' | ||
} | ||
}) | ||
} else { | ||
//transaction is rolled black and nothing is created in the database | ||
) | ||
result2.records.forEach(r => console.log(r.get('name'))) | ||
console.log('Second query completed') | ||
await txc.commit() | ||
console.log('committed') | ||
} catch (error) { | ||
console.log(error) | ||
await txc.rollback() | ||
console.log('rolled back') | ||
tx.rollback() | ||
} finally { | ||
await session.close() | ||
} | ||
``` | ||
Subscriber API allows following combinations of `onNext`, `onCompleted` and `onError` callback invocations: | ||
#### With Reactive Session | ||
- zero or more `onNext` followed by `onCompleted` when operation was successful. `onError` will not be invoked | ||
in this case | ||
- zero or more `onNext` followed by `onError` when operation failed. Callback `onError` might be invoked after | ||
couple `onNext` invocations because records are streamed lazily by the database. `onCompleted` will not be invoked | ||
in this case | ||
```javascript | ||
rxSession | ||
.beginTransaction() | ||
.pipe( | ||
mergeMap(txc => | ||
concatWith( | ||
txc | ||
.run( | ||
'MERGE (bob:Person {name: $nameParam}) RETURN bob.name AS name', | ||
{ | ||
nameParam: 'Bob' | ||
} | ||
) | ||
.records() | ||
.pipe(map(r => r.get('name'))), | ||
of('First query completed'), | ||
txc | ||
.run( | ||
'MERGE (adam:Person {name: $nameParam}) RETURN adam.name AS name', | ||
{ | ||
nameParam: 'Adam' | ||
} | ||
) | ||
.records() | ||
.pipe(map(r => r.get('name'))), | ||
of('Second query completed'), | ||
txc.commit(), | ||
of('committed') | ||
).pipe(catchError(err => txc.rollback().pipe(throwError(() => err)))) | ||
) | ||
) | ||
.subscribe({ | ||
next: data => console.log(data), | ||
complete: () => console.log('completed'), | ||
error: error => console.log(error) | ||
}) | ||
``` | ||
## Parallelization | ||
### Numbers and the Integer type | ||
In a single session, multiple queries will be executed serially. In order to parallelize queries, multiple sessions are required. | ||
The Neo4j type system uses 64-bit signed integer values. The range of values is between `-(2`<sup>`64`</sup>`- 1)` and `(2`<sup>`63`</sup>`- 1)`. | ||
## Building | ||
However, JavaScript can only safely represent integers between `Number.MIN_SAFE_INTEGER` `-(2`<sup>`53`</sup>`- 1)` and `Number.MAX_SAFE_INTEGER` `(2`<sup>`53`</sup>`- 1)`. | ||
npm install | ||
npm run build | ||
In order to support the full Neo4j type system, the driver will not automatically convert to javascript integers. | ||
Any time the driver receives an integer value from Neo4j, it will be represented with an internal integer type by the driver. | ||
This produces browser-compatible standalone files under `lib/browser` and a Node.js module version under `lib/`. | ||
See files under `examples/` on how to use. | ||
_**Any javascript number value passed as a parameter will be recognized as `Float` type.**_ | ||
## Testing | ||
#### Writing integers | ||
Tests **require** latest [Boltkit](https://github.com/neo4j-contrib/boltkit) to be installed in the system. It is needed to start, stop and configure local test database. Boltkit can be installed with the following command: | ||
Numbers written directly e.g. `session.run("CREATE (n:Node {age: $age})", {age: 22})` will be of type `Float` in Neo4j. | ||
pip install --upgrade boltkit | ||
To run tests against "default" Neo4j version: | ||
./runTests.sh | ||
To run tests against specified Neo4j version: | ||
./runTests.sh '-e 3.1.3' | ||
Simple `npm test` can also be used if you already have a running version of a compatible Neo4j server. | ||
For development, you can have the build tool rerun the tests each time you change | ||
the source code: | ||
gulp watch-n-test | ||
### Testing on windows | ||
Running tests on windows requires PhantomJS installed and its bin folder added in windows system variable `Path`. | ||
To run the same test suite, run `.\runTest.ps1` instead in powershell with admin right. | ||
The admin right is required to start/stop Neo4j properly as a system service. | ||
While there is no need to grab admin right if you are running tests against an existing Neo4j server using `npm test`. | ||
## A note on numbers and the Integer type | ||
The Neo4j type system includes 64-bit integer values. | ||
However, JavaScript can only safely represent integers between `-(2`<sup>`53`</sup>`- 1)` and `(2`<sup>`53`</sup>`- 1)`. | ||
In order to support the full Neo4j type system, the driver will not automatically convert to javascript integers. | ||
Any time the driver receives an integer value from Neo4j, it will be represented with an internal integer type by the driver. | ||
### Write integers | ||
Number written directly e.g. `session.run("CREATE (n:Node {age: {age}})", {age: 22})` will be of type `Float` in Neo4j. | ||
To write the `age` as an integer the `neo4j.int` method should be used: | ||
@@ -325,9 +466,9 @@ | ||
session.run('CREATE (n {age: {myIntParam}})', { myIntParam: neo4j.int(22) }) | ||
session.run('CREATE (n {age: $myIntParam})', { myIntParam: neo4j.int(22) }) | ||
``` | ||
To write integers larger than can be represented as JavaScript numbers, use a string argument to `neo4j.int`: | ||
To write an integer value that are not within the range of `Number.MIN_SAFE_INTEGER` `-(2`<sup>`53`</sup>`- 1)` and `Number.MAX_SAFE_INTEGER` `(2`<sup>`53`</sup>`- 1)`, use a string argument to `neo4j.int`: | ||
```javascript | ||
session.run('CREATE (n {age: {myIntParam}})', { | ||
session.run('CREATE (n {age: $myIntParam})', { | ||
myIntParam: neo4j.int('9223372036854775807') | ||
@@ -337,24 +478,27 @@ }) | ||
### Read integers | ||
#### Reading integers | ||
Since Integers can be larger than can be represented as JavaScript numbers, it is only safe to convert to JavaScript numbers if you know that they will not exceed `(2`<sup>`53`</sup>`- 1)` in size. | ||
In Neo4j, the type Integer can be larger what can be represented safely as an integer with JavaScript Number. | ||
It is only safe to convert to a JavaScript Number if you know that the number will be in the range `Number.MIN_SAFE_INTEGER` `-(2`<sup>`53`</sup>`- 1)` and `Number.MAX_SAFE_INTEGER` `(2`<sup>`53`</sup>`- 1)`. | ||
In order to facilitate working with integers the driver include `neo4j.isInt`, `neo4j.integer.inSafeRange`, `neo4j.integer.toNumber`, and `neo4j.integer.toString`. | ||
```javascript | ||
var aSmallInteger = neo4j.int(123) | ||
if (neo4j.integer.inSafeRange(aSmallInteger)) { | ||
var aNumber = aSmallInteger.toNumber() | ||
var smallInteger = neo4j.int(123) | ||
if (neo4j.integer.inSafeRange(smallInteger)) { | ||
var aNumber = smallInteger.toNumber() | ||
} | ||
``` | ||
If you will be handling integers larger than that, you should convert them to strings: | ||
If you will be handling integers that is not within the JavaScript safe range of integers, you should convert the value to a string: | ||
```javascript | ||
var aLargerInteger = neo4j.int('9223372036854775807') | ||
if (!neo4j.integer.inSafeRange(aLargerInteger)) { | ||
var integerAsString = aLargerInteger.toString() | ||
var largeInteger = neo4j.int('9223372036854775807') | ||
if (!neo4j.integer.inSafeRange(largeInteger)) { | ||
var integerAsString = largeInteger.toString() | ||
} | ||
``` | ||
### Enable native numbers | ||
#### Enabling native numbers | ||
@@ -368,6 +512,93 @@ Starting from 1.6 version of the driver it is possible to configure it to only return native numbers instead of custom `Integer` objects. | ||
var driver = neo4j.driver( | ||
'bolt://localhost', | ||
neo4j.auth.basic('neo4j', 'neo4j'), | ||
'neo4j://localhost', | ||
neo4j.auth.basic('neo4j', 'password'), | ||
{ disableLosslessIntegers: true } | ||
) | ||
``` | ||
## Building | ||
``` | ||
npm ci | ||
npm run build | ||
``` | ||
This produces browser-compatible standalone files under `lib/browser` and a Node.js module version under `lib/`. | ||
See files under `examples/` on how to use. | ||
## Testing | ||
Tests **require** latest [Testkit 4.3](https://github.com/neo4j-drivers/testkit/tree/4.3), Python3 and Docker. | ||
Testkit is needed to be cloned and configured to run against the Javascript Lite Driver. Use the following steps to configure Testkit. | ||
1. Clone the Testkit repository | ||
``` | ||
git clone https://github.com/neo4j-drivers/testkit.git | ||
``` | ||
2. Under the Testkit folder, install the requirements. | ||
``` | ||
pip3 install -r requirements.txt | ||
``` | ||
3. Define some enviroment variables to configure Testkit | ||
``` | ||
export TEST_DRIVER_NAME=javascript | ||
export TEST_DRIVER_REPO=<path for the root folder of driver repository> | ||
unset TEST_DRIVER_LITE | ||
``` | ||
To run test against against some Neo4j version: | ||
``` | ||
python3 main.py | ||
``` | ||
More details about how to use Teskit could be found on [its repository](https://github.com/neo4j-drivers/testkit/tree/4.3) | ||
## Testing (Legacy) | ||
Tests **require** latest [Boltkit](https://github.com/neo4j-contrib/boltkit) and [Firefox](https://www.mozilla.org/firefox/) to be installed in the system. | ||
Boltkit is needed to start, stop and configure local test database. Boltkit can be installed with the following command: | ||
``` | ||
pip3 install --upgrade boltkit | ||
``` | ||
To run tests against "default" Neo4j version: | ||
``` | ||
./runTests.sh | ||
``` | ||
To run tests against specified Neo4j version: | ||
``` | ||
./runTests.sh '-e 4.2.0' | ||
``` | ||
Simple `npm test` can also be used if you already have a running version of a compatible Neo4j server. | ||
For development, you can have the build tool rerun the tests each time you change | ||
the source code: | ||
``` | ||
gulp watch-n-test | ||
``` | ||
If the `gulp` command line tool is not available, you might need to install this globally: | ||
``` | ||
npm install -g gulp-cli | ||
``` | ||
### Testing on windows | ||
To run the same test suite, run `.\runTest.ps1` instead in powershell with admin right. | ||
The admin right is required to start/stop Neo4j properly as a system service. | ||
While there is no need to grab admin right if you are running tests against an existing Neo4j server using `npm test`. |
{ | ||
"spec_dir": "test", | ||
"spec_files": ["**/*.test.js", "!**/browser/*.js"], | ||
"helpers": ["../node_modules/@babel/register/lib/node.js"], | ||
"stopSpecOnExpectationFailure": false, | ||
"random": true | ||
} |
@@ -6,4 +6,8 @@ { | ||
"noImplicitAny": true, | ||
"noImplicitReturns": true | ||
} | ||
"noImplicitReturns": true, | ||
"strictNullChecks": true, | ||
"moduleResolution": "node", | ||
"types": [] | ||
}, | ||
"include": ["types/**/*.ts", "test/types/**/*.ts"] | ||
} |
/** | ||
* Copyright (c) 2002-2019 "Neo4j," | ||
* Copyright (c) "Neo4j" | ||
* Neo4j Sweden AB [http://neo4j.com] | ||
@@ -20,60 +20,21 @@ * | ||
import Session from './session' | ||
import { Parameters } from './statement-runner' | ||
import { Neo4jError } from './error' | ||
import { ServerInfo } from './result-summary' | ||
import RxSession from './session-rx' | ||
import { | ||
Driver as CoreDriver, | ||
types, | ||
SessionConfig | ||
} from 'neo4j-driver-core' | ||
declare interface AuthToken { | ||
scheme: string | ||
principal: string | ||
credentials: string | ||
realm?: string | ||
parameters?: Parameters | ||
} | ||
declare type AuthToken = types.AuthToken | ||
declare type Config = types.Config | ||
declare type EncryptionLevel = types.EncryptionLevel | ||
declare type TrustStrategy = types.TrustStrategy | ||
declare type EncryptionLevel = 'ENCRYPTION_ON' | 'ENCRYPTION_OFF' | ||
declare type TrustStrategy = | ||
| 'TRUST_ALL_CERTIFICATES' | ||
| 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' | ||
| 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES' | ||
declare type SessionMode = types.SessionMode | ||
declare type LogLevel = 'error' | 'warn' | 'info' | 'debug' | ||
declare interface LoggingConfig { | ||
level?: LogLevel | ||
logger: (level: LogLevel, message: string) => void | ||
} | ||
declare interface Config { | ||
encrypted?: boolean | EncryptionLevel | ||
trust?: TrustStrategy | ||
trustedCertificates?: string[] | ||
knownHosts?: string | ||
maxConnectionPoolSize?: number | ||
maxTransactionRetryTime?: number | ||
maxConnectionLifetime?: number | ||
connectionTimeout?: number | ||
disableLosslessIntegers?: boolean | ||
logging?: LoggingConfig | ||
} | ||
declare type SessionMode = 'READ' | 'WRITE' | ||
declare const READ: SessionMode | ||
declare const WRITE: SessionMode | ||
declare interface Driver { | ||
session({ | ||
defaultAccessMode, | ||
bookmarks, | ||
database | ||
}?: { | ||
defaultAccessMode?: SessionMode | ||
bookmarks?: string | string[] | ||
database?: string | ||
}): Session | ||
close(): void | ||
verifyConnectivity(): Promise<ServerInfo> | ||
declare class Driver extends CoreDriver { | ||
rxSession: (sessionParams?: SessionConfig) => RxSession | ||
} | ||
@@ -80,0 +41,0 @@ |
/** | ||
* Copyright (c) 2002-2019 "Neo4j," | ||
* Copyright (c) "Neo4j" | ||
* Neo4j Sweden AB [http://neo4j.com] | ||
@@ -20,12 +20,14 @@ * | ||
import Integer, { inSafeRange, int, isInt, toNumber, toString } from './integer' | ||
import { | ||
Node, | ||
Path, | ||
PathSegment, | ||
Relationship, | ||
UnboundRelationship | ||
} from './graph-types' | ||
import { isPoint, Point } from './spatial-types' | ||
import { | ||
Neo4jError, | ||
isRetriableError, | ||
error, | ||
Integer, | ||
inSafeRange, | ||
int, | ||
isInt, | ||
toNumber, | ||
toString, | ||
isPoint, | ||
Point, | ||
Date, | ||
@@ -40,14 +42,17 @@ DateTime, | ||
isTime, | ||
isNode, | ||
isPath, | ||
isPathSegment, | ||
isRelationship, | ||
isUnboundRelationship, | ||
LocalDateTime, | ||
LocalTime, | ||
Time | ||
} from './temporal-types' | ||
import { | ||
Neo4jError, | ||
PROTOCOL_ERROR, | ||
SERVICE_UNAVAILABLE, | ||
SESSION_EXPIRED | ||
} from './error' | ||
import Result, { Observer, StatementResult } from './result' | ||
import ResultSummary, { | ||
Time, | ||
Node, | ||
Path, | ||
PathSegment, | ||
Relationship, | ||
UnboundRelationship, | ||
Record, | ||
ResultSummary, | ||
Notification, | ||
@@ -58,6 +63,14 @@ NotificationPosition, | ||
ServerInfo, | ||
StatementStatistic | ||
} from './result-summary' | ||
import Record from './record' | ||
import Session from './session' | ||
QueryStatistics, | ||
Result, | ||
ResultObserver, | ||
QueryResult, | ||
Transaction, | ||
ManagedTransaction, | ||
Session, | ||
BookmarkManager, | ||
bookmarkManager, | ||
BookmarkManagerConfig, | ||
SessionConfig | ||
} from 'neo4j-driver-core' | ||
import { | ||
@@ -73,4 +86,7 @@ AuthToken, | ||
} from './driver' | ||
import Transaction from './transaction' | ||
import { Parameters } from './statement-runner' | ||
import RxSession from './session-rx' | ||
import RxTransaction from './transaction-rx' | ||
import RxManagedTransaction from './transaction-managed-rx' | ||
import RxResult from './result-rx' | ||
import { Parameters } from './query-runner' | ||
@@ -82,2 +98,4 @@ declare const auth: { | ||
bearer: (base64EncodedToken: string) => AuthToken | ||
custom: ( | ||
@@ -92,3 +110,3 @@ principal: string, | ||
declare function driver( | ||
declare function driver ( | ||
url: string, | ||
@@ -99,11 +117,16 @@ authToken?: AuthToken, | ||
declare function hasReachableServer ( | ||
url: string, | ||
config?: Pick<Config, 'logging'> | ||
): Promise<true> | ||
declare const types: { | ||
Node: Node | ||
Relationship: Relationship | ||
UnboundRelationship: UnboundRelationship | ||
PathSegment: PathSegment | ||
Path: Path | ||
Result: Result | ||
ResultSummary: ResultSummary | ||
Record: Record | ||
Node: typeof Node | ||
Relationship: typeof Relationship | ||
UnboundRelationship: typeof UnboundRelationship | ||
PathSegment: typeof PathSegment | ||
Path: typeof Path | ||
Result: typeof Result | ||
ResultSummary: typeof ResultSummary | ||
Record: typeof Record | ||
Point: typeof Point | ||
@@ -116,2 +139,7 @@ Duration: typeof Duration | ||
DateTime: typeof DateTime | ||
Integer: typeof Integer | ||
RxSession: typeof RxSession | ||
RxTransaction: typeof RxTransaction | ||
RxManagedTransaction: typeof RxManagedTransaction | ||
RxResult: typeof RxResult | ||
} | ||
@@ -124,8 +152,2 @@ | ||
declare const error: { | ||
SERVICE_UNAVAILABLE: typeof SERVICE_UNAVAILABLE | ||
SESSION_EXPIRED: typeof SESSION_EXPIRED | ||
PROTOCOL_ERROR: typeof PROTOCOL_ERROR | ||
} | ||
declare const integer: { | ||
@@ -150,2 +172,10 @@ toNumber: typeof toNumber | ||
declare const graph: { | ||
isNode: typeof isNode | ||
isPath: typeof isPath | ||
isPathSegment: typeof isPathSegment | ||
isRelationship: typeof isRelationship | ||
isUnboundRelationship: typeof isUnboundRelationship | ||
} | ||
/* | ||
@@ -162,2 +192,3 @@ Both default and non-default exports declare all visible types so that they can be used in client code like this: | ||
driver: typeof driver | ||
hasReachableServer: typeof hasReachableServer | ||
int: typeof int | ||
@@ -170,5 +201,6 @@ isInt: typeof isInt | ||
error: typeof error | ||
graph: typeof graph | ||
spatial: typeof spatial | ||
temporal: typeof temporal | ||
Driver: Driver | ||
Driver: typeof Driver | ||
AuthToken: AuthToken | ||
@@ -179,30 +211,36 @@ Config: Config | ||
SessionMode: SessionMode | ||
Neo4jError: Neo4jError | ||
Node: Node | ||
Relationship: Relationship | ||
UnboundRelationship: UnboundRelationship | ||
PathSegment: PathSegment | ||
Path: Path | ||
Integer: Integer | ||
Record: Record | ||
Result: Result | ||
StatementResult: StatementResult | ||
Observer: Observer | ||
ResultSummary: ResultSummary | ||
Plan: Plan | ||
ProfiledPlan: ProfiledPlan | ||
StatementStatistic: StatementStatistic | ||
Notification: Notification | ||
ServerInfo: ServerInfo | ||
Neo4jError: typeof Neo4jError | ||
isRetriableError: typeof isRetriableError | ||
Node: typeof Node | ||
Relationship: typeof Relationship | ||
UnboundRelationship: typeof UnboundRelationship | ||
PathSegment: typeof PathSegment | ||
Path: typeof Path | ||
Integer: typeof Integer | ||
Record: typeof Record | ||
Result: typeof Result | ||
QueryResult: QueryResult | ||
ResultObserver: ResultObserver | ||
ResultSummary: typeof ResultSummary | ||
Plan: typeof Plan | ||
ProfiledPlan: typeof ProfiledPlan | ||
QueryStatistics: typeof QueryStatistics | ||
Notification: typeof Notification | ||
ServerInfo: typeof ServerInfo | ||
NotificationPosition: NotificationPosition | ||
Session: Session | ||
Transaction: Transaction | ||
Point: Point | ||
Session: typeof Session | ||
Transaction: typeof Transaction | ||
ManagedTransaction: typeof ManagedTransaction | ||
Point: typeof Point | ||
isPoint: typeof isPoint | ||
Duration: Duration | ||
LocalTime: LocalTime | ||
Time: Time | ||
Date: Date | ||
LocalDateTime: LocalDateTime | ||
DateTime: DateTime | ||
Duration: typeof Duration | ||
LocalTime: typeof LocalTime | ||
Time: typeof Time | ||
Date: typeof Date | ||
LocalDateTime: typeof LocalDateTime | ||
DateTime: typeof DateTime | ||
RxSession: typeof RxSession | ||
RxTransaction: typeof RxTransaction | ||
RxManagedTransaction: typeof RxManagedTransaction | ||
RxResult: typeof RxResult | ||
isDuration: typeof isDuration | ||
@@ -214,2 +252,8 @@ isLocalTime: typeof isLocalTime | ||
isDateTime: typeof isDateTime | ||
isNode: typeof isNode | ||
isPath: typeof isPath | ||
isPathSegment: typeof isPathSegment | ||
isRelationship: typeof isRelationship | ||
isUnboundRelationship: typeof isUnboundRelationship | ||
bookmarkManager: typeof bookmarkManager | ||
} | ||
@@ -219,2 +263,3 @@ | ||
driver, | ||
hasReachableServer, | ||
int, | ||
@@ -227,2 +272,3 @@ isInt, | ||
error, | ||
graph, | ||
spatial, | ||
@@ -237,2 +283,3 @@ temporal, | ||
Neo4jError, | ||
isRetriableError, | ||
Node, | ||
@@ -246,8 +293,8 @@ Relationship, | ||
Result, | ||
StatementResult, | ||
Observer, | ||
QueryResult, | ||
ResultObserver, | ||
ResultSummary, | ||
Plan, | ||
ProfiledPlan, | ||
StatementStatistic, | ||
QueryStatistics, | ||
Notification, | ||
@@ -258,2 +305,3 @@ ServerInfo, | ||
Transaction, | ||
ManagedTransaction, | ||
Point, | ||
@@ -267,2 +315,6 @@ isPoint, | ||
DateTime, | ||
RxSession, | ||
RxTransaction, | ||
RxManagedTransaction, | ||
RxResult, | ||
isDuration, | ||
@@ -273,5 +325,17 @@ isLocalTime, | ||
isLocalDateTime, | ||
isDateTime | ||
isDateTime, | ||
isNode, | ||
isPath, | ||
isPathSegment, | ||
isRelationship, | ||
isUnboundRelationship, | ||
bookmarkManager | ||
} | ||
export type { | ||
BookmarkManager, | ||
BookmarkManagerConfig, | ||
SessionConfig | ||
} | ||
export default forExport |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 3 instances in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
3808362
43
62861
2
593
0
1
30
1
+ Addedrxjs@^7.8.0
+ Addedbase64-js@1.5.1(transitive)
+ Addedbuffer@6.0.3(transitive)
+ Addedieee754@1.2.1(transitive)
+ Addedneo4j-driver-bolt-connection@3.8.0(transitive)
+ Addedneo4j-driver-core@3.8.0(transitive)
+ Addedrxjs@7.8.1(transitive)
+ Addedsafe-buffer@5.2.1(transitive)
+ Addedstring_decoder@1.3.0(transitive)
+ Addedtslib@2.8.0(transitive)
- Removed@babel/runtime@^7.4.4
- Removedtext-encoding-utf-8@^1.0.2
- Removeduri-js@^4.2.2
- Removed@babel/runtime@7.25.7(transitive)
- Removedpunycode@2.3.1(transitive)
- Removedregenerator-runtime@0.14.1(transitive)
- Removedtext-encoding-utf-8@1.0.2(transitive)
- Removeduri-js@4.4.1(transitive)