From 70eb49d46085fd1c2900de9ba952e0eebab5ab64 Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Wed, 13 Apr 2022 18:50:12 +0200 Subject: [PATCH 01/13] Standardize code and fix linter issues --- packages/testkit-backend/src/backend.js | 5 +- packages/testkit-backend/src/channel/index.js | 6 +- .../testkit-backend/src/channel/interface.js | 6 +- .../testkit-backend/src/channel/socket.js | 14 +- .../src/channel/testkit-protocol.js | 7 +- .../testkit-backend/src/channel/websocket.js | 15 +- packages/testkit-backend/src/context.js | 4 +- .../src/controller/interface.js | 3 +- .../testkit-backend/src/controller/local.js | 8 +- .../testkit-backend/src/controller/remote.js | 23 ++- .../src/cypher-native-binders.js | 147 +++++++++--------- packages/testkit-backend/src/feature/async.js | 2 +- .../testkit-backend/src/feature/common.js | 10 +- packages/testkit-backend/src/feature/index.js | 5 +- packages/testkit-backend/src/index.js | 24 +-- .../src/request-handlers-rx.js | 58 ++++--- .../testkit-backend/src/request-handlers.js | 58 +++---- packages/testkit-backend/src/responses.js | 8 +- .../src/skipped-tests/browser.js | 2 +- .../src/skipped-tests/common.js | 8 +- .../src/skipped-tests/index.js | 4 +- packages/testkit-backend/src/stringify.js | 2 +- .../testkit-backend/src/summary-binder.js | 16 +- 23 files changed, 209 insertions(+), 226 deletions(-) diff --git a/packages/testkit-backend/src/backend.js b/packages/testkit-backend/src/backend.js index f84e432ee..0278019fd 100644 --- a/packages/testkit-backend/src/backend.js +++ b/packages/testkit-backend/src/backend.js @@ -1,5 +1,5 @@ -import Channel from './channel' -import Controller from './controller' +import Channel from './channel' // eslint-disable-line no-unused-vars +import Controller from './controller' // eslint-disable-line no-unused-vars /** * Binds Channel and Controller @@ -39,5 +39,4 @@ export default class Backend { this._channel.stop() this._controller.stop() } - } diff --git a/packages/testkit-backend/src/channel/index.js b/packages/testkit-backend/src/channel/index.js index 3f6350362..b97684bed 100644 --- a/packages/testkit-backend/src/channel/index.js +++ b/packages/testkit-backend/src/channel/index.js @@ -1,6 +1,6 @@ -import Channel from "./interface" -import SocketChannel from "./socket" -import WebSocketChannel from "./websocket" +import Channel from './interface' +import SocketChannel from './socket' +import WebSocketChannel from './websocket' /** * Channels are the pieces of code responsible for communicating with testkit. * diff --git a/packages/testkit-backend/src/channel/interface.js b/packages/testkit-backend/src/channel/interface.js index 9cadfdea1..478a30573 100644 --- a/packages/testkit-backend/src/channel/interface.js +++ b/packages/testkit-backend/src/channel/interface.js @@ -1,4 +1,4 @@ -import { EventEmitter } from "events" +import { EventEmitter } from 'events' /** * Defines the interface used for receiving commands form teskit. @@ -10,7 +10,6 @@ import { EventEmitter } from "events" * @event request This event is triggered when the channel receives a request */ export default class Channel extends EventEmitter { - start () { throw Error('Not implemented') } @@ -24,7 +23,6 @@ export default class Channel extends EventEmitter { } writeBackendError (contextId, error) { - this.writeResponse(contextId, { name: 'BackendError', data: { msg: error } }) + this.writeResponse(contextId, { name: 'BackendError', data: { msg: error } }) } - } diff --git a/packages/testkit-backend/src/channel/socket.js b/packages/testkit-backend/src/channel/socket.js index 37e440688..89d471dc2 100644 --- a/packages/testkit-backend/src/channel/socket.js +++ b/packages/testkit-backend/src/channel/socket.js @@ -13,7 +13,7 @@ function generateRandomId () { * This implementation is meant to be run in NodeJS, it doesn't support Browser. */ export default class SocketChannel extends Channel { - constructor(port, newProtocol = stream => new Protocol(stream), newId = generateRandomId ) { + constructor (port, newProtocol = stream => new Protocol(stream), newId = generateRandomId) { super() this._newProtocol = newProtocol this._server = null @@ -34,9 +34,9 @@ export default class SocketChannel extends Channel { } } - _handleConnection(connection) { + _handleConnection (connection) { console.log('Backend connected') - + const contextId = this._newId() const protocol = this._newProtocol(connection) @@ -46,10 +46,10 @@ export default class SocketChannel extends Channel { }) this.emit('contextOpen', { contextId }) - protocol.on('request', request => this.emit('request', { contextId, request }) ) + protocol.on('request', request => this.emit('request', { contextId, request })) protocol.on('error', e => this._writeBackendError(contextId, e)) - - connection.on('end', () => { + + connection.on('end', () => { if (this._clients.has(contextId)) { this._clients.get(contextId).protocol.stop() } @@ -69,7 +69,7 @@ export default class SocketChannel extends Channel { } writeBackendError (contextId, error) { - this.writeResponse(contextId, { name: 'BackendError', data: { msg: error } }) + this.writeResponse(contextId, { name: 'BackendError', data: { msg: error } }) } stop () { diff --git a/packages/testkit-backend/src/channel/testkit-protocol.js b/packages/testkit-backend/src/channel/testkit-protocol.js index 1670566a3..e8b1f2d60 100644 --- a/packages/testkit-backend/src/channel/testkit-protocol.js +++ b/packages/testkit-backend/src/channel/testkit-protocol.js @@ -11,7 +11,7 @@ export default class Protocol extends EventEmitter { this._readlineInterface = null } - start() { + start () { if (!this._readlineInterface) { this._readlineInterface = readline.createInterface(this._stream, null) this._readlineInterface.on('line', this._processLine.bind(this)) @@ -56,14 +56,14 @@ export default class Protocol extends EventEmitter { } } - _emitError(e) { + _emitError (e) { this.emit('error', e) } serializeResponse (response) { console.log('> writing response', response) const responseStr = stringify(response) - return ['#response begin', responseStr, '#response end'].join('\n') + '\n' + return ['#response begin', responseStr, '#response end'].join('\n') + '\n' } _emitRequest () { @@ -72,5 +72,4 @@ export default class Protocol extends EventEmitter { console.log('> Got request ' + name, data) this.emit('request', { name, data }) } - } diff --git a/packages/testkit-backend/src/channel/websocket.js b/packages/testkit-backend/src/channel/websocket.js index 4c8281dfa..26c248433 100644 --- a/packages/testkit-backend/src/channel/websocket.js +++ b/packages/testkit-backend/src/channel/websocket.js @@ -1,4 +1,5 @@ -import Channel from "./interface" +/* eslint-env browser */ +import Channel from './interface' /** * This communication channel is meant to connect to other instances of the `testkit-backend` for receiving its events. @@ -6,21 +7,20 @@ import Channel from "./interface" * This channel is only supported in browsers since it depends on WebSocket client to be available globally. */ export default class WebSocketChannel extends Channel { - - constructor(address) { + constructor (address) { super() this._adddress = address this._ws = null } start () { - if(!this._ws) { + if (!this._ws) { this._ws = new WebSocket(this._adddress) this._ws.onmessage = ({ data: message }) => { console.log(message) console.debug('[WebSocketChannel] Received messsage', message) - const { messageType, contextId, data } = JSON.parse(message) - + const { messageType, contextId, data } = JSON.parse(message) + switch (messageType) { case 'contextOpen': case 'contextClose': @@ -39,7 +39,7 @@ export default class WebSocketChannel extends Channel { } stop () { - if(this._ws) { + if (this._ws) { this._ws.close() this._ws = null } @@ -58,5 +58,4 @@ export default class WebSocketChannel extends Channel { typeof value === 'bigint' ? `${value}n` : value ) } - } diff --git a/packages/testkit-backend/src/context.js b/packages/testkit-backend/src/context.js index bbe8dc234..1153c2fe1 100644 --- a/packages/testkit-backend/src/context.js +++ b/packages/testkit-backend/src/context.js @@ -98,11 +98,11 @@ export default class Context { return Object.values(this._txs).filter(tx => tx.sessionId === sessionId) } - getShouldRunTestFunction() { + getShouldRunTestFunction () { return this._shouldRunTest } - getFeatures() { + getFeatures () { return this._getFeatures() } diff --git a/packages/testkit-backend/src/controller/interface.js b/packages/testkit-backend/src/controller/interface.js index 94e4fd9f6..df5957d4a 100644 --- a/packages/testkit-backend/src/controller/interface.js +++ b/packages/testkit-backend/src/controller/interface.js @@ -7,7 +7,6 @@ import { EventEmitter } from 'events' * @event response Event triggered whith response to the request handled. */ export default class Controller extends EventEmitter { - start () { } @@ -24,7 +23,7 @@ export default class Controller extends EventEmitter { throw new Error('not implemented') } - async handle(contextId, request) { + async handle (contextId, request) { throw new Error('not implemented') } } diff --git a/packages/testkit-backend/src/controller/local.js b/packages/testkit-backend/src/controller/local.js index 5f4471aae..64c46a37c 100644 --- a/packages/testkit-backend/src/controller/local.js +++ b/packages/testkit-backend/src/controller/local.js @@ -3,15 +3,13 @@ import Controller from './interface' import stringify from '../stringify' import { isFrontendError } from '../request-handlers' - /** * Local controller handles the requests locally by redirecting them to the correct request handler/service. * * This controller is used when testing browser and locally. */ export default class LocalController extends Controller { - - constructor(requestHandlers = {}, shouldRunTest = () => {}, getFeatures = () => []) { + constructor (requestHandlers = {}, shouldRunTest = () => {}, getFeatures = () => []) { super() this._requestHandlers = requestHandlers this._shouldRunTest = shouldRunTest @@ -41,7 +39,6 @@ export default class LocalController extends Controller { writeError: (e) => this._writeError(contextId, e), writeBackendError: (msg) => this._writeBackendError(contextId, msg) }) - } _writeResponse (contextId, response) { @@ -57,7 +54,7 @@ export default class LocalController extends Controller { if (e.name) { if (isFrontendError(e)) { this._writeResponse(contextId, newResponse('FrontendError', { - msg: 'Simulating the client code throwing some error.', + msg: 'Simulating the client code throwing some error.' })) } else { const id = this._contexts.get(contextId).addError(e) @@ -71,7 +68,6 @@ export default class LocalController extends Controller { } this._writeBackendError(contextId, e) } - } function newResponse (name, data) { diff --git a/packages/testkit-backend/src/controller/remote.js b/packages/testkit-backend/src/controller/remote.js index 535801b4f..83044c8a0 100644 --- a/packages/testkit-backend/src/controller/remote.js +++ b/packages/testkit-backend/src/controller/remote.js @@ -1,7 +1,7 @@ -import Controller from "./interface" -import { WebSocketServer } from "ws" -import { createServer } from "http" -import { Server } from "node-static" +import Controller from './interface' +import { WebSocketServer } from 'ws' +import { createServer } from 'http' +import { Server } from 'node-static' /** * RemoteController handles the requests by sending them a remote client. @@ -12,7 +12,7 @@ import { Server } from "node-static" * This controller can only be used in Node since it depends on {@link createServer}, {@link WebSocketServer} and {@link Server} */ export default class RemoteController extends Controller { - constructor(port) { + constructor (port) { super() this._staticServer = new Server('./public') this._port = port @@ -33,12 +33,11 @@ export default class RemoteController extends Controller { } if (!this._wss) { this._wss = new WebSocketServer({ server: this._http }) - this._wss.on('connection', safeRun( ws => this._handleClientConnection(ws))) + this._wss.on('connection', safeRun(ws => this._handleClientConnection(ws))) this._wss.on('error', safeRun(error => { console.error('[RemoteController] Server error', error) })) } - } stop () { @@ -47,7 +46,7 @@ export default class RemoteController extends Controller { this._ws = null } - if(this._wss) { + if (this._wss) { this._wss.close() this._wss = null } @@ -78,7 +77,7 @@ export default class RemoteController extends Controller { console.log('[RemoteController] Registering client') this._ws = ws - this._ws.on('message', safeRun(buffer => { + this._ws.on('message', safeRun(buffer => { const message = JSON.parse(buffer.toString()) console.debug('[RemoteController] Received messsage', message) const { contextId, response } = message @@ -105,7 +104,7 @@ export default class RemoteController extends Controller { data } - console.info(`[RemoteController] Sending message`, message) + console.info('[RemoteController] Sending message', message) return this._ws.send(JSON.stringify(message)) } console.error('[RemoteController] There is no client connected') @@ -119,12 +118,10 @@ export default class RemoteController extends Controller { } _writeBackendError (contextId, msg) { - this._writeResponse(contextId, { name: 'BackendError', data: { msg: msg } }) + this._writeResponse(contextId, { name: 'BackendError', data: { msg: msg } }) } - } - function safeRun (func) { return function () { const args = [...arguments] diff --git a/packages/testkit-backend/src/cypher-native-binders.js b/packages/testkit-backend/src/cypher-native-binders.js index c625ab403..a385b5d04 100644 --- a/packages/testkit-backend/src/cypher-native-binders.js +++ b/packages/testkit-backend/src/cypher-native-binders.js @@ -4,30 +4,29 @@ export function valueResponse (name, value) { return { name: name, data: { value: value } } } - export function objectToCypher (obj) { return objectMapper(obj, nativeToCypher) } -export function objectMemberBitIntToNumber (obj, recursive=false) { - return objectMapper(obj, val => { - if(typeof val === 'bigint') { +export function objectMemberBitIntToNumber (obj, recursive = false) { + return objectMapper(obj, val => { + if (typeof val === 'bigint') { return Number(val) } else if (recursive && typeof val === 'object') { return objectMemberBitIntToNumber(val) - } else if (recursive && typeof val === 'array') { + } else if (recursive && Array.isArray(val)) { return val.map(item => objectMemberBitIntToNumber(item, true)) } return val }) } -function objectMapper(obj, mapper) { +function objectMapper (obj, mapper) { if (obj === null || obj === undefined) { return obj } return Object.keys(obj).reduce((acc, key) => { - return {...acc, [key]: mapper(obj[key])} + return { ...acc, [key]: mapper(obj[key]) } }, {}) } @@ -48,71 +47,7 @@ export function nativeToCypher (x) { case 'boolean': return valueResponse('CypherBool', x) case 'object': - if (neo4j.isInt(x)) { - // TODO: Broken!!! - return valueResponse('CypherInt', x.toInt()) - } - if (Array.isArray(x)) { - const values = x.map(nativeToCypher) - return valueResponse('CypherList', values) - } - if (x instanceof neo4j.types.Node) { - const node = { - id: nativeToCypher(x.identity), - labels: nativeToCypher(x.labels), - props: nativeToCypher(x.properties), - elementId: nativeToCypher(x.elementId) - } - return { name: 'CypherNode', data: node } - } - if (x instanceof neo4j.types.Relationship) { - const relationship = { - id: nativeToCypher(x.identity), - startNodeId: nativeToCypher(x.start), - endNodeId: nativeToCypher(x.end), - type: nativeToCypher(x.type), - props: nativeToCypher(x.properties), - elementId: nativeToCypher(x.elementId), - startNodeElementId: nativeToCypher(x.startNodeElementId), - endNodeElementId: nativeToCypher(x.endNodeElementId) - } - return { name: 'CypherRelationship', data: relationship } - } - if (x instanceof neo4j.types.Path) { - const path = x.segments - .map(segment => { - return { - nodes: [segment.end], - relationships: [segment.relationship] - } - }) - .reduce( - (previous, current) => { - return { - nodes: [...previous.nodes, ...current.nodes], - relationships: [ - ...previous.relationships, - ...current.relationships - ] - } - }, - { nodes: [x.start], relationships: [] } - ) - - return { - name: 'CypherPath', - data: { - nodes: nativeToCypher(path.nodes), - relationships: nativeToCypher(path.relationships) - } - } - } - // If all failed, interpret as a map - const map = {} - for (const [key, value] of Object.entries(x)) { - map[key] = nativeToCypher(value) - } - return valueResponse('CypherMap', map) + return valueResponseOfObject(x) } console.log(`type of ${x} is ${typeof x}`) const err = 'Unable to convert ' + x + ' to cypher type' @@ -120,6 +55,74 @@ export function nativeToCypher (x) { throw Error(err) } +function valueResponseOfObject (x) { + if (neo4j.isInt(x)) { + // TODO: Broken!!! + return valueResponse('CypherInt', x.toInt()) + } + if (Array.isArray(x)) { + const values = x.map(nativeToCypher) + return valueResponse('CypherList', values) + } + if (x instanceof neo4j.types.Node) { + const node = { + id: nativeToCypher(x.identity), + labels: nativeToCypher(x.labels), + props: nativeToCypher(x.properties), + elementId: nativeToCypher(x.elementId) + } + return { name: 'CypherNode', data: node } + } + if (x instanceof neo4j.types.Relationship) { + const relationship = { + id: nativeToCypher(x.identity), + startNodeId: nativeToCypher(x.start), + endNodeId: nativeToCypher(x.end), + type: nativeToCypher(x.type), + props: nativeToCypher(x.properties), + elementId: nativeToCypher(x.elementId), + startNodeElementId: nativeToCypher(x.startNodeElementId), + endNodeElementId: nativeToCypher(x.endNodeElementId) + } + return { name: 'CypherRelationship', data: relationship } + } + if (x instanceof neo4j.types.Path) { + const path = x.segments + .map(segment => { + return { + nodes: [segment.end], + relationships: [segment.relationship] + } + }) + .reduce( + (previous, current) => { + return { + nodes: [...previous.nodes, ...current.nodes], + relationships: [ + ...previous.relationships, + ...current.relationships + ] + } + }, + { nodes: [x.start], relationships: [] } + ) + + return { + name: 'CypherPath', + data: { + nodes: nativeToCypher(path.nodes), + relationships: nativeToCypher(path.relationships) + } + } + } + // If all failed, interpret as a map + const map = {} + for (const [key, value] of Object.entries(x)) { + map[key] = nativeToCypher(value) + } + return valueResponse('CypherMap', map) +} + export function cypherToNative (c) { const { name, diff --git a/packages/testkit-backend/src/feature/async.js b/packages/testkit-backend/src/feature/async.js index 510225864..3c637a19f 100644 --- a/packages/testkit-backend/src/feature/async.js +++ b/packages/testkit-backend/src/feature/async.js @@ -2,7 +2,7 @@ const features = [ 'Feature:API:Result.List', 'Feature:API:Result.Peek', 'Optimization:EagerTransactionBegin', - 'Optimization:PullPipelining', + 'Optimization:PullPipelining' ] export default features diff --git a/packages/testkit-backend/src/feature/common.js b/packages/testkit-backend/src/feature/common.js index ac3a83927..45e005157 100644 --- a/packages/testkit-backend/src/feature/common.js +++ b/packages/testkit-backend/src/feature/common.js @@ -4,14 +4,14 @@ const SUPPORTED_TLS = (() => { if (tls.DEFAULT_MAX_VERSION) { const min = Number(tls.DEFAULT_MIN_VERSION.split('TLSv')[1]) const max = Number(tls.DEFAULT_MAX_VERSION.split('TLSv')[1]) - const result = []; - for (let version = min > 1 ? min : 1.1; version <= max; version = Number((version + 0.1).toFixed(1)) ) { + const result = [] + for (let version = min > 1 ? min : 1.1; version <= max; version = Number((version + 0.1).toFixed(1))) { result.push(`Feature:TLS:${version.toFixed(1)}`) } - return result; + return result } - return []; -})(); + return [] +})() const features = [ 'Feature:Auth:Custom', diff --git a/packages/testkit-backend/src/feature/index.js b/packages/testkit-backend/src/feature/index.js index 6f3e815bf..1e95fa4ec 100644 --- a/packages/testkit-backend/src/feature/index.js +++ b/packages/testkit-backend/src/feature/index.js @@ -4,15 +4,14 @@ import asyncFeatures from './async' const featuresByContext = new Map([ ['async', asyncFeatures], - ['rx', rxFeatures], + ['rx', rxFeatures] ]) - export function createGetFeatures (contexts) { const features = contexts .filter(context => featuresByContext.has(context)) .map(context => featuresByContext.get(context)) - .reduce((previous, current) => [ ...previous, ...current ], commonFeatures) + .reduce((previous, current) => [...previous, ...current], commonFeatures) return () => features } diff --git a/packages/testkit-backend/src/index.js b/packages/testkit-backend/src/index.js index 33657b18c..c9a4b16eb 100644 --- a/packages/testkit-backend/src/index.js +++ b/packages/testkit-backend/src/index.js @@ -9,7 +9,7 @@ import * as RX_REQUEST_HANDLERS from './request-handlers-rx.js' /** * Responsible for configure and run the backend server. */ -function main( ) { +function main () { const testEnviroment = process.env.TEST_ENVIRONMENT || 'LOCAL' const channelType = process.env.CHANNEL_TYPE || 'SOCKET' const backendPort = process.env.BACKEND_PORT || 9876 @@ -19,44 +19,44 @@ function main( ) { const sessionTypeDescriptor = sessionType === 'RX' ? 'rx' : 'async' const driverDescriptorList = driverDescriptor .split(',').map(s => s.trim().toLowerCase()) - + const shouldRunTest = getShouldRunTest([...driverDescriptorList, sessionTypeDescriptor]) const getFeatures = createGetFeatures([sessionTypeDescriptor]) const newChannel = () => { - if ( channelType.toUpperCase() === 'WEBSOCKET' ) { + if (channelType.toUpperCase() === 'WEBSOCKET') { return new WebSocketChannel(new URL(`ws://localhost:${backendPort}`)) } return new SocketChannel(backendPort) - } + } const newController = () => { - if ( testEnviroment.toUpperCase() === 'REMOTE' ) { + if (testEnviroment.toUpperCase() === 'REMOTE') { return new RemoteController(webserverPort) } return new LocalController(getRequestHandlers(sessionType), shouldRunTest, getFeatures) } const backend = new Backend(newController, newChannel) - + backend.start() if (process.on) { // cleaning up - process.on('exit', backend.stop.bind(backend)); + process.on('exit', backend.stop.bind(backend)) // Capturing signals - process.on('SIGINT', process.exit.bind(process)); - process.on('SIGUSR1', process.exit.bind(process)); - process.on('SIGUSR2', process.exit.bind(process)); + process.on('SIGINT', process.exit.bind(process)) + process.on('SIGUSR1', process.exit.bind(process)) + process.on('SIGUSR2', process.exit.bind(process)) process.on('uncaughtException', exception => { console.error('UncaughtException', exception) process.exit() - }); + }) } } -function getRequestHandlers(sessionType) { +function getRequestHandlers (sessionType) { if (sessionType.toUpperCase() === 'RX') { return RX_REQUEST_HANDLERS } diff --git a/packages/testkit-backend/src/request-handlers-rx.js b/packages/testkit-backend/src/request-handlers-rx.js index 27419a64c..36a47d76d 100644 --- a/packages/testkit-backend/src/request-handlers-rx.js +++ b/packages/testkit-backend/src/request-handlers-rx.js @@ -1,9 +1,9 @@ -import * as responses from './responses.js'; -import neo4j from './neo4j.js'; +import * as responses from './responses.js' +import neo4j from './neo4j.js' import { cypherToNative } from './cypher-native-binders.js' -import { from } from 'rxjs'; +import { from } from 'rxjs' // Handlers which didn't change depending export { @@ -20,10 +20,10 @@ export { ForcedRoutingTableUpdate, ResultNext, RetryablePositive, - RetryableNegative, -} from './request-handlers.js'; + RetryableNegative +} from './request-handlers.js' -export function NewSession(context, data, wire) { +export function NewSession (context, data, wire) { let { driverId, accessMode, bookmarks, database, fetchSize, impersonatedUser } = data switch (accessMode) { case 'r': @@ -48,7 +48,7 @@ export function NewSession(context, data, wire) { wire.writeResponse(responses.Session({ id })) } -export function SessionClose(context, data, wire) { +export function SessionClose (context, data, wire) { const { sessionId } = data const session = context.getSession(sessionId) return session @@ -58,7 +58,7 @@ export function SessionClose(context, data, wire) { .catch(err => wire.writeError(err)) } -export function SessionRun(context, data, wire) { +export function SessionRun (context, data, wire) { const { sessionId, cypher, params, txMeta: metadata, timeout } = data const session = context.getSession(sessionId) if (params) { @@ -79,12 +79,12 @@ export function SessionRun(context, data, wire) { const it = toAsyncIterator(result) result[Symbol.asyncIterator] = () => it - let id = context.addResult(result) + const id = context.addResult(result) wire.writeResponse(responses.Result({ id })) } -export function ResultConsume(context, data, wire) { +export function ResultConsume (context, data, wire) { const { resultId } = data const result = context.getResult(resultId) @@ -95,8 +95,7 @@ export function ResultConsume(context, data, wire) { }).catch(e => wire.writeError(e)) } - -export function SessionBeginTransaction(context, data, wire) { +export function SessionBeginTransaction (context, data, wire) { const { sessionId, txMeta: metadata, timeout } = data const session = context.getSession(sessionId) @@ -113,11 +112,10 @@ export function SessionBeginTransaction(context, data, wire) { } catch (e) { console.log('got some err: ' + JSON.stringify(e)) wire.writeError(e) - return } } -export function TransactionRun(context, data, wire) { +export function TransactionRun (context, data, wire) { const { txId, cypher, params } = data const tx = context.getTx(txId) if (params) { @@ -135,7 +133,7 @@ export function TransactionRun(context, data, wire) { wire.writeResponse(responses.Result({ id })) } -export function TransactionRollback(context, data, wire) { +export function TransactionRollback (context, data, wire) { const { txId: id } = data const { tx } = context.getTx(id) return tx.rollback() @@ -147,7 +145,7 @@ export function TransactionRollback(context, data, wire) { }) } -export function TransactionCommit(context, data, wire) { +export function TransactionCommit (context, data, wire) { const { txId: id } = data const { tx } = context.getTx(id) return tx.commit() @@ -159,7 +157,7 @@ export function TransactionCommit(context, data, wire) { }) } -export function TransactionClose(context, data, wire) { +export function TransactionClose (context, data, wire) { const { txId: id } = data const { tx } = context.getTx(id) return tx.close() @@ -168,7 +166,7 @@ export function TransactionClose(context, data, wire) { .catch(e => wire.writeError(e)) } -export function SessionReadTransaction(context, data, wire) { +export function SessionReadTransaction (context, data, wire) { const { sessionId, txMeta: metadata } = data const session = context.getSession(sessionId) @@ -184,11 +182,10 @@ export function SessionReadTransaction(context, data, wire) { .catch(e => wire.writeError(e)) } catch (e) { wire.writeError(e) - return } } -export function SessionWriteTransaction(context, data, wire) { +export function SessionWriteTransaction (context, data, wire) { const { sessionId, txMeta: metadata } = data const session = context.getSession(sessionId) @@ -204,24 +201,21 @@ export function SessionWriteTransaction(context, data, wire) { .catch(e => wire.writeError(e)) } catch (e) { wire.writeError(e) - return } } - -function toAsyncIterator(result) { - function queueObserver() { - function createResolvablePromise() { +function toAsyncIterator (result) { + function queueObserver () { + function createResolvablePromise () { const resolvablePromise = {} resolvablePromise.promise = new Promise((resolve, reject) => { resolvablePromise.resolve = resolve resolvablePromise.reject = reject - }); - return resolvablePromise; + }) + return resolvablePromise } - - function isError(elementOrError) { + function isError (elementOrError) { return elementOrError instanceof Error } @@ -238,7 +232,7 @@ function toAsyncIterator(result) { error: (error) => { observer._push(error) }, - _push(element) { + _push (element) { if (promiseHolder.resolvable !== null) { const resolvable = promiseHolder.resolvable promiseHolder.resolvable = null @@ -280,7 +274,7 @@ function toAsyncIterator(result) { throw error } }, - get size() { + get size () { return buffer.length } } @@ -290,7 +284,7 @@ function toAsyncIterator(result) { const records = result.records() const observer = queueObserver() - records.subscribe(observer); + records.subscribe(observer) const state = { finished: false diff --git a/packages/testkit-backend/src/request-handlers.js b/packages/testkit-backend/src/request-handlers.js index 217f7f4d8..5903a9893 100644 --- a/packages/testkit-backend/src/request-handlers.js +++ b/packages/testkit-backend/src/request-handlers.js @@ -1,12 +1,12 @@ import neo4j from './neo4j' import { cypherToNative } from './cypher-native-binders.js' -import * as responses from './responses.js' +import * as responses from './responses.js' -export function throwFrontendError() { - throw new Error("TestKit FrontendError") +export function throwFrontendError () { + throw new Error('TestKit FrontendError') } -export function isFrontendError(error) { +export function isFrontendError (error) { return error.message === 'TestKit FrontendError' } @@ -31,6 +31,7 @@ export function NewDriver (context, data, wire) { break case 'bearer': parsedAuthToken = neo4j.auth.bearer(authToken.credentials) + break default: parsedAuthToken = neo4j.auth.custom( authToken.principal, @@ -42,10 +43,10 @@ export function NewDriver (context, data, wire) { } const resolver = resolverRegistered ? address => - new Promise((resolve, reject) => { - const id = context.addResolverRequest(resolve, reject) - wire.writeResponse(responses.ResolverResolutionRequired({ id, address })) - }) + new Promise((resolve, reject) => { + const id = context.addResolverRequest(resolve, reject) + wire.writeResponse(responses.ResolverResolutionRequired({ id, address })) + }) : undefined const config = { userAgent, @@ -159,7 +160,7 @@ export function SessionRun (context, data, wire) { return } - let id = context.addResult(result) + const id = context.addResult(result) wire.writeResponse(responses.Result({ id })) } @@ -167,7 +168,7 @@ export function SessionRun (context, data, wire) { export function ResultNext (context, data, wire) { const { resultId } = data const result = context.getResult(resultId) - if (!("recordIt" in result)) { + if (!('recordIt' in result)) { result.recordIt = result[Symbol.asyncIterator]() } return result.recordIt.next().then(({ value, done }) => { @@ -179,13 +180,13 @@ export function ResultNext (context, data, wire) { }).catch(e => { console.log('got some err: ' + JSON.stringify(e)) wire.writeError(e) - }); + }) } export function ResultPeek (context, data, wire) { const { resultId } = data const result = context.getResult(resultId) - if (!("recordIt" in result)) { + if (!('recordIt' in result)) { result.recordIt = result[Symbol.asyncIterator]() } return result.recordIt.peek().then(({ value, done }) => { @@ -197,7 +198,7 @@ export function ResultPeek (context, data, wire) { }).catch(e => { console.log('got some err: ' + JSON.stringify(e)) wire.writeError(e) - }); + }) } export function ResultConsume (context, data, wire) { @@ -231,7 +232,7 @@ export function SessionReadTransaction (context, data, wire) { const id = context.addTx(tx, sessionId, resolve, reject) wire.writeResponse(responses.RetryableTry({ id })) }) - , { metadata }) + , { metadata }) .then(_ => wire.writeResponse(responses.RetryableDone())) .catch(error => wire.writeError(error)) } @@ -271,17 +272,16 @@ export function SessionBeginTransaction (context, data, wire) { try { return session.beginTransaction({ metadata, timeout }) - .then(tx => { - const id = context.addTx(tx, sessionId) - wire.writeResponse(responses.Transaction({ id })) - }).catch(e => { - console.log('got some err: ' + JSON.stringify(e)) - wire.writeError(e) - }) + .then(tx => { + const id = context.addTx(tx, sessionId) + wire.writeResponse(responses.Transaction({ id })) + }).catch(e => { + console.log('got some err: ' + JSON.stringify(e)) + wire.writeError(e) + }) } catch (e) { console.log('got some err: ' + JSON.stringify(e)) wire.writeError(e) - return } } @@ -329,7 +329,7 @@ export function SessionWriteTransaction (context, data, wire) { const id = context.addTx(tx, sessionId, resolve, reject) wire.writeResponse(responses.RetryableTry({ id })) }) - , { metadata }) + , { metadata }) .then(_ => wire.writeResponse(responses.RetryableDone())) .catch(error => wire.writeError(error)) } @@ -418,13 +418,13 @@ export function ForcedRoutingTableUpdate (context, { driverId, database, bookmar if (provider._freshRoutingTable) { // Removing database from the routing table registry provider._routingTableRegistry._remove(database) - return provider._freshRoutingTable ({ - accessMode: 'READ', - database, - bookmarks: bookmarks, - onDatabaseNameResolved: () => {} + return provider._freshRoutingTable({ + accessMode: 'READ', + database, + bookmarks: bookmarks, + onDatabaseNameResolved: () => {} }) - .then(() => wire.writeResponse(responses.Driver({ "id": driverId }))) + .then(() => wire.writeResponse(responses.Driver({ id: driverId }))) .catch(error => wire.writeError(error)) } else { wire.writeError('Driver does not support routing') diff --git a/packages/testkit-backend/src/responses.js b/packages/testkit-backend/src/responses.js index 9ae1ec5f9..c0331bc70 100644 --- a/packages/testkit-backend/src/responses.js +++ b/packages/testkit-backend/src/responses.js @@ -40,7 +40,7 @@ export function NullRecord () { export function Record ({ record }) { const values = Array.from(record.values()).map(nativeToCypher) - return response('Record', { values }) + return response('Record', { values }) } export function RecordList ({ records }) { @@ -59,9 +59,9 @@ export function Bookmarks ({ bookmarks }) { } export function ServerInfo ({ serverInfo }) { - return response('ServerInfo', { + return response('ServerInfo', { ...serverInfo, - protocolVersion: serverInfo.protocolVersion.toFixed(1) + protocolVersion: serverInfo.protocolVersion.toFixed(1) }) } @@ -93,6 +93,6 @@ export function FeatureList ({ features }) { return response('FeatureList', { features }) } -function response(name, data) { +function response (name, data) { return { name, data } } diff --git a/packages/testkit-backend/src/skipped-tests/browser.js b/packages/testkit-backend/src/skipped-tests/browser.js index 0ba30d33d..788e1657a 100644 --- a/packages/testkit-backend/src/skipped-tests/browser.js +++ b/packages/testkit-backend/src/skipped-tests/browser.js @@ -9,7 +9,7 @@ const skippedTests = [ ifEndsWith('test_should_check_multi_db_support'), ifEquals('stub.disconnects.test_disconnects.TestDisconnects.test_fail_on_reset'), ifEquals('stub.tx_begin_parameters.test_tx_begin_parameters.TestTxBeginParameters.test_impersonation_fails_on_v4x3'), - ifEquals('stub.session_run_parameters.test_session_run_parameters.TestSessionRunParameters.test_impersonation_fails_on_v4x3'), + ifEquals('stub.session_run_parameters.test_session_run_parameters.TestSessionRunParameters.test_impersonation_fails_on_v4x3') ), skip( 'TLS Tests not implemented for browwer', diff --git a/packages/testkit-backend/src/skipped-tests/common.js b/packages/testkit-backend/src/skipped-tests/common.js index 817c215bc..75731daca 100644 --- a/packages/testkit-backend/src/skipped-tests/common.js +++ b/packages/testkit-backend/src/skipped-tests/common.js @@ -1,4 +1,4 @@ -import skip, { ifEquals, ifEndsWith, ifStartsWith } from './skip' +import skip, { ifEquals, ifEndsWith } from './skip' const skippedTests = [ skip( @@ -43,11 +43,11 @@ const skippedTests = [ 'Partial session iteration is not supported by the js driver', ifEquals('neo4j.sessionrun.TestSessionRun.test_partial_iteration'), ifEquals('neo4j.test_session_run.TestSessionRun.test_session_reuse'), - ifEquals('neo4j.test_session_run.TestSessionRun.test_iteration_nested'), + ifEquals('neo4j.test_session_run.TestSessionRun.test_iteration_nested') ), skip( 'Nested calls does not garauntee order in the records pulling', - ifEquals('stub.iteration.test_iteration_tx_run.TestIterationTxRun.test_nested'), + ifEquals('stub.iteration.test_iteration_tx_run.TestIterationTxRun.test_nested') ), skip( 'The driver has no support domain_name_resolver', @@ -102,7 +102,7 @@ const skippedTests = [ skip( 'Needs to implement "domain_name_resolver_fn"', ifEndsWith( - 'test_should_request_rt_from_all_initial_routers_until_successful_on_unknown_failure', + 'test_should_request_rt_from_all_initial_routers_until_successful_on_unknown_failure' ), ifEndsWith( 'test_should_request_rt_from_all_initial_routers_until_successful_on_authorization_expired' diff --git a/packages/testkit-backend/src/skipped-tests/index.js b/packages/testkit-backend/src/skipped-tests/index.js index 4f135b291..e1ee901be 100644 --- a/packages/testkit-backend/src/skipped-tests/index.js +++ b/packages/testkit-backend/src/skipped-tests/index.js @@ -4,14 +4,14 @@ import rxSessionSkippedTests from './rx' const skippedTestsByContext = new Map([ ['browser', browserSkippedTests], - ['rx', rxSessionSkippedTests], + ['rx', rxSessionSkippedTests] ]) export function getShouldRunTest (contexts) { const skippedTests = contexts .filter(context => skippedTestsByContext.has(context)) .map(context => skippedTestsByContext.get(context)) - .reduce((previous, current) => [ ...previous, ...current ], commonSkippedTests) + .reduce((previous, current) => [...previous, ...current], commonSkippedTests) return (testName, { onRun, onSkip }) => { const { reason } = diff --git a/packages/testkit-backend/src/stringify.js b/packages/testkit-backend/src/stringify.js index 996e6dad4..772a6f3a7 100644 --- a/packages/testkit-backend/src/stringify.js +++ b/packages/testkit-backend/src/stringify.js @@ -1,4 +1,4 @@ -export default function stringify(json) { +export default function stringify (json) { return JSON.stringify(json, (_, value) => typeof value === 'bigint' ? `${value}n` : value ) diff --git a/packages/testkit-backend/src/summary-binder.js b/packages/testkit-backend/src/summary-binder.js index 4dbab6ae7..24e5a46ef 100644 --- a/packages/testkit-backend/src/summary-binder.js +++ b/packages/testkit-backend/src/summary-binder.js @@ -1,6 +1,6 @@ import { objectToCypher, objectMemberBitIntToNumber } from './cypher-native-binders.js' -function mapPlan(plan) { +function mapPlan (plan) { return { operatorType: plan.operatorType, args: plan.arguments, @@ -9,7 +9,7 @@ function mapPlan(plan) { } } -function mapCounters(stats) { +function mapCounters (stats) { return { ...stats._stats, systemUpdates: stats.systemUpdates(), @@ -18,7 +18,7 @@ function mapCounters(stats) { } } -function mapProfile(profile, child=false) { +function mapProfile (profile, child = false) { const mapChild = (child) => mapProfile(child, true) const obj = { args: objectMemberBitIntToNumber(profile.arguments), @@ -30,21 +30,21 @@ function mapProfile(profile, child=false) { } if (child) { - return { + return { ...obj, pageCacheHitRatio: profile.pageCacheHitRatio !== undefined ? Number(profile.pageCacheHitRatio) : undefined, pageCacheHits: profile.pageCacheHits !== undefined ? Number(profile.pageCacheHits) : undefined, pageCacheMisses: profile.pageCacheMisses !== undefined ? Number(profile.pageCacheMisses) : undefined, - time: profile.time !== undefined ? Number(profile.time) : undefined, + time: profile.time !== undefined ? Number(profile.time) : undefined } } return obj } -function mapNotification(notification) { +function mapNotification (notification) { return { ...notification, - position: Object.keys(notification.position).length !== 0 ? notification.position : undefined, + position: Object.keys(notification.position).length !== 0 ? notification.position : undefined } } @@ -58,7 +58,7 @@ export function nativeToTestkitSummary (summary) { }, serverInfo: { agent: summary.server.agent, - protocolVersion: summary.server.protocolVersion.toFixed(1) + protocolVersion: summary.server.protocolVersion.toFixed(1) }, counters: mapCounters(summary.counters), plan: mapPlan(summary.plan), From 00959bed9c6708366ced7f0dba6f94aafcaf0f3c Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Thu, 14 Apr 2022 17:55:23 +0200 Subject: [PATCH 02/13] Applying linter to packages/core/src --- packages/core/src/auth.ts | 6 +- packages/core/src/connection-provider.ts | 18 +- packages/core/src/connection.ts | 13 +- packages/core/src/driver.ts | 79 ++++--- packages/core/src/error.ts | 6 +- packages/core/src/graph-types.ts | 44 ++-- packages/core/src/index.ts | 4 +- packages/core/src/integer.ts | 211 +++++++++--------- packages/core/src/internal/bookmarks.ts | 22 +- .../core/src/internal/connection-holder.ts | 115 +++++----- packages/core/src/internal/logger.ts | 60 ++--- packages/core/src/internal/observers.ts | 59 +++-- .../resolver/base-host-name-resolver.ts | 1 + .../resolver/configured-custom-resolver.ts | 10 +- packages/core/src/internal/server-address.ts | 24 +- packages/core/src/internal/temporal-util.ts | 16 +- .../core/src/internal/transaction-executor.ts | 43 ++-- packages/core/src/internal/tx-config.ts | 18 +- packages/core/src/internal/url-util.ts | 86 +++---- packages/core/src/internal/util.ts | 49 ++-- packages/core/src/json.ts | 2 +- packages/core/src/record.ts | 33 +-- packages/core/src/result-summary.ts | 102 +++++---- packages/core/src/result.ts | 185 ++++++++------- packages/core/src/session.ts | 95 ++++---- packages/core/src/spatial-types.ts | 16 +- packages/core/src/temporal-types.ts | 78 +++---- packages/core/src/transaction-managed.ts | 14 +- packages/core/src/transaction-promise.ts | 88 ++++---- packages/core/src/transaction.ts | 78 +++---- packages/core/src/types.ts | 8 +- 31 files changed, 810 insertions(+), 773 deletions(-) diff --git a/packages/core/src/auth.ts b/packages/core/src/auth.ts index 0a193e90c..502166a0e 100644 --- a/packages/core/src/auth.ts +++ b/packages/core/src/auth.ts @@ -29,7 +29,7 @@ */ const auth = { basic: (username: string, password: string, realm?: string) => { - if (realm) { + if (realm != null) { return { scheme: 'basic', principal: username, @@ -77,12 +77,12 @@ const auth = { } } -function isNotEmpty(value: T | null | undefined): boolean { +function isNotEmpty (value: T | null | undefined): boolean { return !( value === null || value === undefined || value === '' || - Object.getPrototypeOf(value) === Object.prototype && Object.keys(value).length === 0 + (Object.getPrototypeOf(value) === Object.prototype && Object.keys(value).length === 0) ) } diff --git a/packages/core/src/connection-provider.ts b/packages/core/src/connection-provider.ts index 5398018da..a6b2bb53d 100644 --- a/packages/core/src/connection-provider.ts +++ b/packages/core/src/connection-provider.ts @@ -16,12 +16,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable @typescript-eslint/promise-function-async */ import Connection from './connection' import { bookmarks } from './internal' import { ServerInfo } from './result-summary' - /** * Inteface define a common way to acquire a connection * @@ -44,11 +44,11 @@ class ConnectionProvider { * @property {string} param.impersonatedUser - the impersonated user * @property {function (databaseName:string?)} param.onDatabaseNameResolved - Callback called when the database name get resolved */ - acquireConnection(param?: { + acquireConnection (param?: { accessMode?: string database?: string - bookmarks: bookmarks.Bookmarks, - impersonatedUser?: string, + bookmarks: bookmarks.Bookmarks + impersonatedUser?: string onDatabaseNameResolved?: (databaseName?: string) => void }): Promise { throw Error('Not implemented') @@ -60,7 +60,7 @@ class ConnectionProvider { * * @returns {Promise} */ - supportsMultiDb(): Promise { + supportsMultiDb (): Promise { throw Error('Not implemented') } @@ -70,7 +70,7 @@ class ConnectionProvider { * * @returns {Promise} */ - supportsTransactionConfig(): Promise { + supportsTransactionConfig (): Promise { throw Error('Not implemented') } @@ -80,7 +80,7 @@ class ConnectionProvider { * * @returns {Promise} */ - supportsUserImpersonation(): Promise { + supportsUserImpersonation (): Promise { throw Error('Not implemented') } @@ -94,7 +94,7 @@ class ConnectionProvider { * * @returns {Promise} promise resolved with server info or rejected with error. */ - verifyConnectivityAndGetServerInfo(param? :{ database?: string, accessMode?: string }): Promise { + verifyConnectivityAndGetServerInfo (param?: { database?: string, accessMode?: string }): Promise { throw Error('Not implemented') } @@ -103,7 +103,7 @@ class ConnectionProvider { * * @returns {Promise} */ - close(): Promise { + close (): Promise { throw Error('Not implemented') } } diff --git a/packages/core/src/connection.ts b/packages/core/src/connection.ts index 4fb8eb9b4..54e81276e 100644 --- a/packages/core/src/connection.ts +++ b/packages/core/src/connection.ts @@ -16,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable @typescript-eslint/promise-function-async */ import { ServerAddress } from './internal/server-address' @@ -25,28 +26,28 @@ import { ServerAddress } from './internal/server-address' */ class Connection { get id (): string { - return "" + return '' } - get databaseId(): string { - return "" + get databaseId (): string { + return '' } - get server(): any { + get server (): any { return {} } /** * @property {ServerAddress} the server address this connection is opened against */ - get address(): ServerAddress | undefined { + get address (): ServerAddress | undefined { return undefined } /** * @property {ServerVersion} the version of the server this connection is connected to */ - get version(): any { + get version (): any { return undefined } diff --git a/packages/core/src/driver.ts b/packages/core/src/driver.ts index 257181d57..9e2b7d641 100644 --- a/packages/core/src/driver.ts +++ b/packages/core/src/driver.ts @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +/* eslint-disable @typescript-eslint/promise-function-async */ import ConnectionProvider from './connection-provider' import { Bookmarks } from './internal/bookmarks' import ConfiguredCustomResolver from './internal/resolver/configured-custom-resolver' @@ -32,7 +32,7 @@ import { import { Logger } from './internal/logger' import Session from './session' import { ServerInfo } from './result-summary' -import { ENCRYPTION_ON, ENCRYPTION_OFF } from './internal/util' +import { ENCRYPTION_ON } from './internal/util' import { EncryptionLevel, LoggingConfig, @@ -85,7 +85,7 @@ type CreateSession = (args: { database: string config: any reactive: boolean - fetchSize: number, + fetchSize: number impersonatedUser?: string }) => Session @@ -122,9 +122,9 @@ class Driver { * @param {Object} meta Metainformation about the driver * @param {Object} config * @param {function(id: number, config:Object, log:Logger, hostNameResolver: ConfiguredCustomResolver): ConnectionProvider } createConnectonProvider Creates the connection provider - * @param {function(args): Session } createSession Creates the a session + * @param {function(args): Session } createSession Creates the a session */ - constructor( + constructor ( meta: MetaInfo, config: DriverConfig = {}, createConnectonProvider: CreateConnectionProvider, @@ -139,7 +139,7 @@ class Driver { this._id = idGenerator++ this._meta = meta this._config = config - this._log = log; + this._log = log this._createConnectionProvider = createConnectonProvider this._createSession = createSession @@ -156,7 +156,7 @@ class Driver { /** * Verifies connectivity of this driver by trying to open a connection with the provided driver options. * - * @deprecated This return of this method will change in 6.0.0 to not async return the {@link ServerInfo} and + * @deprecated This return of this method will change in 6.0.0 to not async return the {@link ServerInfo} and * async return {@link void} instead. If you need to use the server info, use {@link getServerInfo} instead. * * @public @@ -164,9 +164,7 @@ class Driver { * @param {string} param.database - The target database to verify connectivity for. * @returns {Promise} promise resolved with server info or rejected with error. */ - verifyConnectivity({ database = '' }: { database?: string } = {}): Promise< - ServerInfo - > { + verifyConnectivity ({ database = '' }: { database?: string } = {}): Promise { const connectionProvider = this._getOrCreateConnectionProvider() return connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode: READ }) } @@ -178,7 +176,7 @@ class Driver { * @param {string} param.database - The target database to verify connectivity for. * @returns {Promise} promise resolved with void or rejected with error. */ - getServerInfo({ database = ''}: { database?: string } = {}): Promise { + getServerInfo ({ database = '' }: { database?: string } = {}): Promise { const connectionProvider = this._getOrCreateConnectionProvider() return connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode: READ }) } @@ -191,7 +189,7 @@ class Driver { * * @returns {Promise} promise resolved with a boolean or rejected with error. */ - supportsMultiDb(): Promise { + supportsMultiDb (): Promise { const connectionProvider = this._getOrCreateConnectionProvider() return connectionProvider.supportsMultiDb() } @@ -204,7 +202,7 @@ class Driver { * * @returns {Promise} promise resolved with a boolean or rejected with error. */ - supportsTransactionConfig(): Promise { + supportsTransactionConfig (): Promise { const connectionProvider = this._getOrCreateConnectionProvider() return connectionProvider.supportsTransactionConfig() } @@ -217,7 +215,7 @@ class Driver { * * @returns {Promise} promise resolved with a boolean or rejected with error. */ - supportsUserImpersonation(): Promise { + supportsUserImpersonation (): Promise { const connectionProvider = this._getOrCreateConnectionProvider() return connectionProvider.supportsUserImpersonation() } @@ -227,7 +225,7 @@ class Driver { * * @returns {boolean} */ - isEncrypted(): boolean { + isEncrypted (): boolean { return this._isEncrypted() } @@ -235,7 +233,7 @@ class Driver { * @protected * @returns {boolean} */ - _supportsRouting(): boolean { + _supportsRouting (): boolean { return this._meta.routing } @@ -245,7 +243,7 @@ class Driver { * @protected * @returns {boolean} */ - _isEncrypted() { + _isEncrypted (): boolean { return this._config.encrypted === ENCRYPTION_ON || this._config.encrypted === true } @@ -255,7 +253,7 @@ class Driver { * @protected * @returns {TrustStrategy} */ - _getTrust(): TrustStrategy | undefined { + _getTrust (): TrustStrategy | undefined { return this._config.trust } @@ -281,7 +279,7 @@ class Driver { * @param {string} param.impersonatedUser - The username which the user wants to impersonate for the duration of the session. * @return {Session} new session. */ - session({ + session ({ defaultAccessMode = WRITE, bookmarks: bookmarkOrBookmarks, database = '', @@ -300,7 +298,8 @@ class Driver { database, reactive: false, impersonatedUser, - fetchSize: validateFetchSizeValue(fetchSize, this._config.fetchSize!!) + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + fetchSize: validateFetchSizeValue(fetchSize, this._config.fetchSize!) }) } @@ -310,9 +309,9 @@ class Driver { * @public * @return {Promise} promise resolved when the driver is closed. */ - close(): Promise { + close (): Promise { this._log.info(`Driver ${this._id} closing`) - if (this._connectionProvider) { + if (this._connectionProvider != null) { return this._connectionProvider.close() } return Promise.resolve() @@ -321,16 +320,16 @@ class Driver { /** * @protected */ - _afterConstruction() { + _afterConstruction (): void { this._log.info( - `${this._meta.typename} driver ${this._id} created for server address ${this._meta.address}` + `${this._meta.typename} driver ${this._id} created for server address ${this._meta.address.toString()}` ) } /** * @private */ - _newSession({ + _newSession ({ defaultAccessMode, bookmarkOrBookmarks, database, @@ -344,15 +343,15 @@ class Driver { reactive: boolean impersonatedUser?: string fetchSize: number - }) { + }): Session { const sessionMode = Session._validateSessionMode(defaultAccessMode) const connectionProvider = this._getOrCreateConnectionProvider() - const bookmarks = bookmarkOrBookmarks + const bookmarks = bookmarkOrBookmarks != null ? new Bookmarks(bookmarkOrBookmarks) : Bookmarks.empty() return this._createSession({ mode: sessionMode, - database: database || '', + database: database ?? '', connectionProvider, bookmarks, config: this._config, @@ -365,8 +364,8 @@ class Driver { /** * @private */ - _getOrCreateConnectionProvider(): ConnectionProvider { - if (!this._connectionProvider) { + _getOrCreateConnectionProvider (): ConnectionProvider { + if (this._connectionProvider == null) { this._connectionProvider = this._createConnectionProvider( this._id, this._config, @@ -383,17 +382,17 @@ class Driver { * @private * @returns {Object} the given config. */ -function validateConfig(config: any, log: Logger): any { +function validateConfig (config: any, log: Logger): any { const resolver = config.resolver - if (resolver && typeof resolver !== 'function') { + if (resolver !== null && resolver !== undefined && typeof resolver !== 'function') { throw new TypeError( - `Configured resolver should be a function. Got: ${resolver}` + `Configured resolver should be a function. Got: ${typeof resolver}` ) } if (config.connectionAcquisitionTimeout < config.connectionTimeout) { log.warn( - 'Configuration for "connectionAcquisitionTimeout" should be greater than ' + + 'Configuration for "connectionAcquisitionTimeout" should be greater than ' + 'or equal to "connectionTimeout". Otherwise, the connection acquisition ' + 'timeout will take precedence for over the connection timeout in scenarios ' + 'where a new connection is created while it is acquired' @@ -405,7 +404,7 @@ function validateConfig(config: any, log: Logger): any { /** * @private */ -function sanitizeConfig(config: any) { +function sanitizeConfig (config: any): void { config.maxConnectionLifetime = sanitizeIntValue( config.maxConnectionLifetime, DEFAULT_MAX_CONNECTION_LIFETIME @@ -428,7 +427,7 @@ function sanitizeConfig(config: any) { /** * @private */ -function sanitizeIntValue(rawValue: any, defaultWhenAbsent: number): number { +function sanitizeIntValue (rawValue: any, defaultWhenAbsent: number): number { const sanitizedValue = parseInt(rawValue, 10) if (sanitizedValue > 0 || sanitizedValue === 0) { return sanitizedValue @@ -442,7 +441,7 @@ function sanitizeIntValue(rawValue: any, defaultWhenAbsent: number): number { /** * @private */ -function validateFetchSizeValue( +function validateFetchSizeValue ( rawValue: any, defaultWhenAbsent: number ): number { @@ -466,10 +465,10 @@ function extractConnectionTimeout (config: any): number|null { if (configuredTimeout === 0) { // timeout explicitly configured to 0 return null - } else if (configuredTimeout && configuredTimeout < 0) { + } else if (!isNaN(configuredTimeout) && configuredTimeout < 0) { // timeout explicitly configured to a negative value return null - } else if (!configuredTimeout) { + } else if (isNaN(configuredTimeout)) { // timeout not configured, use default value return DEFAULT_CONNECTION_TIMEOUT_MILLIS } else { @@ -483,7 +482,7 @@ function extractConnectionTimeout (config: any): number|null { * @returns {ConfiguredCustomResolver} new custom resolver that wraps the passed-in resolver function. * If resolved function is not specified, it defaults to an identity resolver. */ -function createHostNameResolver(config: any): ConfiguredCustomResolver { +function createHostNameResolver (config: any): ConfiguredCustomResolver { return new ConfiguredCustomResolver(config.resolver) } diff --git a/packages/core/src/error.ts b/packages/core/src/error.ts index dcec636af..1af6464e7 100644 --- a/packages/core/src/error.ts +++ b/packages/core/src/error.ts @@ -90,7 +90,7 @@ class Neo4jError extends Error { * @param {object|undefined|null} error the error object * @returns {boolean} true if the error is retriable */ - static isRetriable(error?: any | null): boolean { + static isRetriable (error?: any | null): boolean { return error !== null && error !== undefined && error instanceof Neo4jError && @@ -116,7 +116,7 @@ function newError (message: string, code?: Neo4jErrorCode): Neo4jError { * @param {object|undefined|null} error the error object * @returns {boolean} true if the error is retriable */ - const isRetriableError = Neo4jError.isRetriable +const isRetriableError = Neo4jError.isRetriable /** * @private @@ -141,7 +141,7 @@ function _isRetriableTransientError (code?: Neo4jErrorCode): boolean { // terminated. These are really client errors but classification on the server is not entirely correct and // they are classified as transient. - if (code !== undefined && code.indexOf('TransientError') >= 0) { + if (code?.includes('TransientError') === true) { if ( code === 'Neo.TransientError.Transaction.Terminated' || code === 'Neo.TransientError.Transaction.LockClientStopped' diff --git a/packages/core/src/graph-types.ts b/packages/core/src/graph-types.ts index 06f648979..03c0ff859 100644 --- a/packages/core/src/graph-types.ts +++ b/packages/core/src/graph-types.ts @@ -24,7 +24,7 @@ type StandardDate = Date * @typedef {number | Integer | bigint} NumberOrInteger */ type NumberOrInteger = number | Integer | bigint -type Properties = { [key: string]: any } +interface Properties { [key: string]: any } const IDENTIFIER_PROPERTY_ATTRIBUTES = { value: true, @@ -40,8 +40,8 @@ const UNBOUND_RELATIONSHIP_IDENTIFIER_PROPERTY: string = const PATH_IDENTIFIER_PROPERTY: string = '__isPath__' const PATH_SEGMENT_IDENTIFIER_PROPERTY: string = '__isPathSegment__' -function hasIdentifierProperty(obj: any, property: string): boolean { - return (obj && obj[property]) === true +function hasIdentifierProperty (obj: any, property: string): boolean { + return obj != null && obj[property] === true } /** @@ -60,7 +60,7 @@ class Node 0) { @@ -228,7 +228,7 @@ Object.defineProperty( * @param {Object} obj the object to test. * @return {boolean} `true` if given object is a {@link Relationship}, `false` otherwise. */ -function isRelationship(obj: object): obj is Relationship { +function isRelationship (obj: object): obj is Relationship { return hasIdentifierProperty(obj, RELATIONSHIP_IDENTIFIER_PROPERTY) } @@ -250,7 +250,7 @@ class UnboundRelationship { + bind (start: T, end: T): Relationship { return new Relationship( this.identity, start, end, this.type, this.properties, - this.elementId, + this.elementId ) } @@ -303,7 +303,7 @@ class UnboundRelationship, end: Node): Relationship { + bindTo (start: Node, end: Node): Relationship { return new Relationship( this.identity, start.identity, @@ -312,14 +312,14 @@ class UnboundRelationship 0) { @@ -346,7 +346,7 @@ Object.defineProperty( * @param {Object} obj the object to test. * @return {boolean} `true` if given object is a {@link UnboundRelationship}, `false` otherwise. */ -function isUnboundRelationship(obj: object): obj is UnboundRelationship { +function isUnboundRelationship (obj: object): obj is UnboundRelationship { return hasIdentifierProperty(obj, UNBOUND_RELATIONSHIP_IDENTIFIER_PROPERTY) } @@ -364,7 +364,7 @@ class PathSegment { * @param {Relationship} rel - relationship that connects start and end node * @param {Node} end - end node */ - constructor(start: Node, rel: Relationship, end: Node) { + constructor (start: Node, rel: Relationship, end: Node) { /** * Start node. * @type {Node} @@ -394,7 +394,7 @@ Object.defineProperty( * @param {Object} obj the object to test. * @return {boolean} `true` if given object is a {@link PathSegment}, `false` otherwise. */ -function isPathSegment(obj: object): obj is PathSegment { +function isPathSegment (obj: object): obj is PathSegment { return hasIdentifierProperty(obj, PATH_SEGMENT_IDENTIFIER_PROPERTY) } @@ -404,7 +404,7 @@ function isPathSegment(obj: object): obj is PathSegment { class Path { start: Node end: Node - segments: PathSegment[] + segments: Array> length: number /** * @constructor @@ -413,7 +413,7 @@ class Path { * @param {Node} end - end node * @param {Array} segments - Array of Segments */ - constructor(start: Node, end: Node, segments: PathSegment[]) { + constructor (start: Node, end: Node, segments: Array>) { /** * Start node. * @type {Node} @@ -448,7 +448,7 @@ Object.defineProperty( * @param {Object} obj the object to test. * @return {boolean} `true` if given object is a {@link Path}, `false` otherwise. */ -function isPath(obj: object): obj is Path { +function isPath (obj: object): obj is Path { return hasIdentifierProperty(obj, PATH_IDENTIFIER_PROPERTY) } @@ -470,5 +470,5 @@ export { } export type { StandardDate, - NumberOrInteger, + NumberOrInteger } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 6f05d54b1..47cf53a9b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -214,7 +214,7 @@ export type { NotificationPosition, QueryResult, ResultObserver, - TransactionConfig, -}; + TransactionConfig +} export default forExport diff --git a/packages/core/src/integer.ts b/packages/core/src/integer.ts index 9c859d046..e94ad5486 100644 --- a/packages/core/src/integer.ts +++ b/packages/core/src/integer.ts @@ -50,20 +50,20 @@ class Integer { low: number high: number - constructor(low?: number, high?: number) { + constructor (low?: number, high?: number) { /** * The low 32 bits as a signed value. * @type {number} * @expose */ - this.low = low || 0 + this.low = low ?? 0 /** * The high 32 bits as a signed value. * @type {number} * @expose */ - this.high = high || 0 + this.high = high ?? 0 } // The internal representation of an Integer is the two given signed, 32-bit values. @@ -83,7 +83,7 @@ class Integer { // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from* // methods on which they depend. - inSafeRange(): boolean { + inSafeRange (): boolean { return ( this.greaterThanOrEqual(Integer.MIN_SAFE_VALUE) && this.lessThanOrEqual(Integer.MAX_SAFE_VALUE) @@ -95,7 +95,7 @@ class Integer { * @returns {number} * @expose */ - toInt(): number { + toInt (): number { return this.low } @@ -104,7 +104,7 @@ class Integer { * @returns {number} * @expose */ - toNumber(): number { + toNumber (): number { return this.high * TWO_PWR_32_DBL + (this.low >>> 0) } @@ -113,7 +113,7 @@ class Integer { * @returns {bigint} * @expose */ - toBigInt(): bigint { + toBigInt (): bigint { if (this.isZero()) { return BigInt(0) } else if (this.isPositive()) { @@ -136,7 +136,7 @@ class Integer { * @return {number} * @package */ - toNumberOrInfinity(): number { + toNumberOrInfinity (): number { if (this.lessThan(Integer.MIN_SAFE_VALUE)) { return Number.NEGATIVE_INFINITY } else if (this.greaterThan(Integer.MAX_SAFE_VALUE)) { @@ -154,10 +154,10 @@ class Integer { * @throws {RangeError} If `radix` is out of range * @expose */ - toString(radix?: number): string { - radix = radix || 10 + toString (radix?: number): string { + radix = radix ?? 10 if (radix < 2 || radix > 36) { - throw RangeError('radix out of range: ' + radix) + throw RangeError('radix out of range: ' + radix.toString()) } if (this.isZero()) { return '0' @@ -167,8 +167,8 @@ class Integer { if (this.equals(Integer.MIN_VALUE)) { // We need to change the Integer value before it can be negated, so we remove // the bottom-most digit in this base and then recurse to do the rest. - var radixInteger = Integer.fromNumber(radix) - var div = this.div(radixInteger) + const radixInteger = Integer.fromNumber(radix) + const div = this.div(radixInteger) rem = div.multiply(radixInteger).subtract(this) return div.toString(radix) + rem.toInt().toString(radix) } else { @@ -178,13 +178,13 @@ class Integer { // Do several (6) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. - var radixToPower = Integer.fromNumber(Math.pow(radix, 6)) + const radixToPower = Integer.fromNumber(Math.pow(radix, 6)) rem = this - var result = '' + let result = '' while (true) { - var remDiv = rem.div(radixToPower) - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0 - var digits = intval.toString(radix) + const remDiv = rem.div(radixToPower) + const intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0 + let digits = intval.toString(radix) rem = remDiv if (rem.isZero()) { return digits + result @@ -202,7 +202,7 @@ class Integer { * @returns {number} Signed high bits * @expose */ - getHighBits(): number { + getHighBits (): number { return this.high } @@ -211,7 +211,7 @@ class Integer { * @returns {number} Signed low bits * @expose */ - getLowBits(): number { + getLowBits (): number { return this.low } @@ -220,12 +220,13 @@ class Integer { * @returns {number} * @expose */ - getNumBitsAbs(): number { + getNumBitsAbs (): number { if (this.isNegative()) { return this.equals(Integer.MIN_VALUE) ? 64 : this.negate().getNumBitsAbs() } - var val = this.high !== 0 ? this.high : this.low - for (var bit = 31; bit > 0; bit--) { + const val = this.high !== 0 ? this.high : this.low + let bit = 0 + for (bit = 31; bit > 0; bit--) { if ((val & (1 << bit)) !== 0) { break } @@ -238,7 +239,7 @@ class Integer { * @returns {boolean} * @expose */ - isZero(): boolean { + isZero (): boolean { return this.high === 0 && this.low === 0 } @@ -247,7 +248,7 @@ class Integer { * @returns {boolean} * @expose */ - isNegative(): boolean { + isNegative (): boolean { return this.high < 0 } @@ -256,7 +257,7 @@ class Integer { * @returns {boolean} * @expose */ - isPositive(): boolean { + isPositive (): boolean { return this.high >= 0 } @@ -265,7 +266,7 @@ class Integer { * @returns {boolean} * @expose */ - isOdd(): boolean { + isOdd (): boolean { return (this.low & 1) === 1 } @@ -274,7 +275,7 @@ class Integer { * @returns {boolean} * @expose */ - isEven(): boolean { + isEven (): boolean { return (this.low & 1) === 0 } @@ -284,7 +285,7 @@ class Integer { * @returns {boolean} * @expose */ - equals(other: Integerable): boolean { + equals (other: Integerable): boolean { const theOther = Integer.fromValue(other) return this.high === theOther.high && this.low === theOther.low } @@ -295,7 +296,7 @@ class Integer { * @returns {boolean} * @expose */ - notEquals(other: Integerable): boolean { + notEquals (other: Integerable): boolean { return !this.equals(/* validates */ other) } @@ -305,7 +306,7 @@ class Integer { * @returns {boolean} * @expose */ - lessThan(other: Integerable): boolean { + lessThan (other: Integerable): boolean { return this.compare(/* validates */ other) < 0 } @@ -315,7 +316,7 @@ class Integer { * @returns {boolean} * @expose */ - lessThanOrEqual(other: Integerable): boolean { + lessThanOrEqual (other: Integerable): boolean { return this.compare(/* validates */ other) <= 0 } @@ -325,7 +326,7 @@ class Integer { * @returns {boolean} * @expose */ - greaterThan(other: Integerable): boolean { + greaterThan (other: Integerable): boolean { return this.compare(/* validates */ other) > 0 } @@ -335,7 +336,7 @@ class Integer { * @returns {boolean} * @expose */ - greaterThanOrEqual(other: Integerable): boolean { + greaterThanOrEqual (other: Integerable): boolean { return this.compare(/* validates */ other) >= 0 } @@ -346,14 +347,14 @@ class Integer { * if the given one is greater * @expose */ - compare(other: Integerable): number { + compare (other: Integerable): number { const theOther = Integer.fromValue(other) if (this.equals(theOther)) { return 0 } - var thisNeg = this.isNegative() - var otherNeg = theOther.isNegative() + const thisNeg = this.isNegative() + const otherNeg = theOther.isNegative() if (thisNeg && !otherNeg) { return -1 } @@ -369,7 +370,7 @@ class Integer { * @returns {!Integer} Negated Integer * @expose */ - negate(): Integer { + negate (): Integer { if (this.equals(Integer.MIN_VALUE)) { return Integer.MIN_VALUE } @@ -382,25 +383,25 @@ class Integer { * @returns {!Integer} Sum * @expose */ - add(addend: Integerable): Integer { + add (addend: Integerable): Integer { const theAddend = Integer.fromValue(addend) // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - var a48 = this.high >>> 16 - var a32 = this.high & 0xffff - var a16 = this.low >>> 16 - var a00 = this.low & 0xffff + const a48 = this.high >>> 16 + const a32 = this.high & 0xffff + const a16 = this.low >>> 16 + const a00 = this.low & 0xffff - var b48 = theAddend.high >>> 16 - var b32 = theAddend.high & 0xffff - var b16 = theAddend.low >>> 16 - var b00 = theAddend.low & 0xffff + const b48 = theAddend.high >>> 16 + const b32 = theAddend.high & 0xffff + const b16 = theAddend.low >>> 16 + const b00 = theAddend.low & 0xffff - var c48 = 0 - var c32 = 0 - var c16 = 0 - var c00 = 0 + let c48 = 0 + let c32 = 0 + let c16 = 0 + let c00 = 0 c00 += a00 + b00 c16 += c00 >>> 16 c00 &= 0xffff @@ -421,7 +422,7 @@ class Integer { * @returns {!Integer} Difference * @expose */ - subtract(subtrahend: Integerable): Integer { + subtract (subtrahend: Integerable): Integer { const theSubtrahend = Integer.fromValue(subtrahend) return this.add(theSubtrahend.negate()) } @@ -432,7 +433,7 @@ class Integer { * @returns {!Integer} Product * @expose */ - multiply(multiplier: Integerable): Integer { + multiply (multiplier: Integerable): Integer { if (this.isZero()) { return Integer.ZERO } @@ -469,20 +470,20 @@ class Integer { // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. // We can skip products that would overflow. - var a48 = this.high >>> 16 - var a32 = this.high & 0xffff - var a16 = this.low >>> 16 - var a00 = this.low & 0xffff + const a48 = this.high >>> 16 + const a32 = this.high & 0xffff + const a16 = this.low >>> 16 + const a00 = this.low & 0xffff - var b48 = theMultiplier.high >>> 16 - var b32 = theMultiplier.high & 0xffff - var b16 = theMultiplier.low >>> 16 - var b00 = theMultiplier.low & 0xffff + const b48 = theMultiplier.high >>> 16 + const b32 = theMultiplier.high & 0xffff + const b16 = theMultiplier.low >>> 16 + const b00 = theMultiplier.low & 0xffff - var c48 = 0 - var c32 = 0 - var c16 = 0 - var c00 = 0 + let c48 = 0 + let c32 = 0 + let c16 = 0 + let c00 = 0 c00 += a00 * b00 c16 += c00 >>> 16 c00 &= 0xffff @@ -512,7 +513,7 @@ class Integer { * @returns {!Integer} Quotient * @expose */ - div(divisor: Integerable): Integer { + div (divisor: Integerable): Integer { const theDivisor = Integer.fromValue(divisor) if (theDivisor.isZero()) { @@ -521,7 +522,7 @@ class Integer { if (this.isZero()) { return Integer.ZERO } - var approx, rem, res + let approx, rem, res if (this.equals(Integer.MIN_VALUE)) { if ( theDivisor.equals(Integer.ONE) || @@ -533,7 +534,7 @@ class Integer { return Integer.ONE } else { // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1) + const halfThis = this.shiftRight(1) approx = halfThis.div(theDivisor).shiftLeft(1) if (approx.equals(Integer.ZERO)) { return theDivisor.isNegative() ? Integer.ONE : Integer.NEG_ONE @@ -571,13 +572,13 @@ class Integer { // We will tweak the approximate result by changing it in the 48-th digit or // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2) - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48) + const log2 = Math.ceil(Math.log(approx) / Math.LN2) + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48) // Decrease the approximation until it is smaller than the remainder. Note // that if it is too large, the product overflows and is negative. - var approxRes = Integer.fromNumber(approx) - var approxRem = approxRes.multiply(theDivisor) + let approxRes = Integer.fromNumber(approx) + let approxRem = approxRes.multiply(theDivisor) while (approxRem.isNegative() || approxRem.greaterThan(rem)) { approx -= delta approxRes = Integer.fromNumber(approx) @@ -602,7 +603,7 @@ class Integer { * @returns {!Integer} Remainder * @expose */ - modulo(divisor: Integerable): Integer { + modulo (divisor: Integerable): Integer { const theDivisor = Integer.fromValue(divisor) return this.subtract(this.div(theDivisor).multiply(theDivisor)) } @@ -612,7 +613,7 @@ class Integer { * @returns {!Integer} * @expose */ - not(): Integer { + not (): Integer { return Integer.fromBits(~this.low, ~this.high) } @@ -622,7 +623,7 @@ class Integer { * @returns {!Integer} * @expose */ - and(other: Integerable): Integer { + and (other: Integerable): Integer { const theOther = Integer.fromValue(other) return Integer.fromBits(this.low & theOther.low, this.high & theOther.high) } @@ -633,7 +634,7 @@ class Integer { * @returns {!Integer} * @expose */ - or(other: Integerable): Integer { + or (other: Integerable): Integer { const theOther = Integer.fromValue(other) return Integer.fromBits(this.low | theOther.low, this.high | theOther.high) } @@ -644,7 +645,7 @@ class Integer { * @returns {!Integer} * @expose */ - xor(other: Integerable): Integer { + xor (other: Integerable): Integer { const theOther = Integer.fromValue(other) return Integer.fromBits(this.low ^ theOther.low, this.high ^ theOther.high) } @@ -655,7 +656,7 @@ class Integer { * @returns {!Integer} Shifted Integer * @expose */ - shiftLeft(numBits: number | Integer): Integer { + shiftLeft (numBits: number | Integer): Integer { let bitsCount = Integer.toNumber(numBits) if ((bitsCount &= 63) === 0) { return Integer.ZERO @@ -675,7 +676,7 @@ class Integer { * @returns {!Integer} Shifted Integer * @expose */ - shiftRight(numBits: number | Integer): Integer { + shiftRight (numBits: number | Integer): Integer { let bitsCount: number = Integer.toNumber(numBits) if ((bitsCount &= 63) === 0) { @@ -764,8 +765,8 @@ class Integer { * @returns {boolean} * @expose */ - static isInteger(obj: any): obj is Integer { - return (obj && obj.__isInteger__) === true + static isInteger (obj: any): obj is Integer { + return obj?.__isInteger__ === true } /** @@ -775,16 +776,16 @@ class Integer { * @returns {!Integer} The corresponding Integer value * @expose */ - static fromInt(value: number): Integer { - var obj, cachedObj + static fromInt (value: number): Integer { + let cachedObj value = value | 0 if (value >= -128 && value < 128) { cachedObj = INT_CACHE.get(value) - if (cachedObj) { + if (cachedObj != null) { return cachedObj } } - obj = new Integer(value, value < 0 ? -1 : 0) + const obj = new Integer(value, value < 0 ? -1 : 0) if (value >= -128 && value < 128) { INT_CACHE.set(value, obj) } @@ -800,7 +801,7 @@ class Integer { * @returns {!Integer} The corresponding Integer value * @expose */ - static fromBits(lowBits: number, highBits: number): Integer { + static fromBits (lowBits: number, highBits: number): Integer { return new Integer(lowBits, highBits) } @@ -811,7 +812,7 @@ class Integer { * @returns {!Integer} The corresponding Integer value * @expose */ - static fromNumber(value: number): Integer { + static fromNumber (value: number): Integer { if (isNaN(value) || !isFinite(value)) { return Integer.ZERO } @@ -835,7 +836,7 @@ class Integer { * @returns {!Integer} The corresponding Integer value * @expose */ - static fromString(str: string, radix?: number): Integer { + static fromString (str: string, radix?: number): Integer { if (str.length === 0) { throw newError('number format error: empty string') } @@ -847,9 +848,9 @@ class Integer { ) { return Integer.ZERO } - radix = radix || 10 + radix = radix ?? 10 if (radix < 2 || radix > 36) { - throw newError('radix out of range: ' + radix) + throw newError('radix out of range: ' + radix.toString()) } let p: number @@ -864,11 +865,11 @@ class Integer { const radixToPower = Integer.fromNumber(Math.pow(radix, 8)) let result = Integer.ZERO - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i) - var value = parseInt(str.substring(i, i + size), radix) + for (let i = 0; i < str.length; i += 8) { + const size = Math.min(8, str.length - i) + const value = parseInt(str.substring(i, i + size), radix) if (size < 8) { - var power = Integer.fromNumber(Math.pow(radix, size)) + const power = Integer.fromNumber(Math.pow(radix, size)) result = result.multiply(power).add(Integer.fromNumber(value)) } else { result = result.multiply(radixToPower) @@ -885,7 +886,7 @@ class Integer { * @returns {!Integer} * @expose */ - static fromValue(val: Integerable): Integer { + static fromValue (val: Integerable): Integer { if (val /* is compatible */ instanceof Integer) { return val } @@ -909,7 +910,7 @@ class Integer { * @returns {number} * @expose */ - static toNumber(val: Integerable): number { + static toNumber (val: Integerable): number { switch (typeof val) { case 'number': return val @@ -928,7 +929,7 @@ class Integer { * @returns {string} * @expose */ - static toString(val: Integerable, radix?: number): string { + static toString (val: Integerable, radix?: number): string { return Integer.fromValue(val).toString(radix) } @@ -940,7 +941,7 @@ class Integer { * @returns {boolean} * @expose */ - static inSafeRange(val: Integerable): boolean { + static inSafeRange (val: Integerable): boolean { return Integer.fromValue(val).inSafeRange() } } @@ -949,7 +950,7 @@ type Integerable = | number | string | Integer - | { low: number; high: number } + | { low: number, high: number } | bigint Object.defineProperty(Integer.prototype, '__isInteger__', { @@ -964,7 +965,7 @@ Object.defineProperty(Integer.prototype, '__isInteger__', { * @inner * @private */ -var TWO_PWR_16_DBL = 1 << 16 +const TWO_PWR_16_DBL = 1 << 16 /** * @type {number} @@ -972,7 +973,7 @@ var TWO_PWR_16_DBL = 1 << 16 * @inner * @private */ -var TWO_PWR_24_DBL = 1 << 24 +const TWO_PWR_24_DBL = 1 << 24 /** * @type {number} @@ -980,7 +981,7 @@ var TWO_PWR_24_DBL = 1 << 24 * @inner * @private */ -var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL +const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL /** * @type {number} @@ -988,7 +989,7 @@ var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL * @inner * @private */ -var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL +const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL /** * @type {number} @@ -996,7 +997,7 @@ var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL * @inner * @private */ -var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2 +const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2 /** * @type {!Integer} @@ -1004,7 +1005,7 @@ var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2 * @inner * @private */ -var TWO_PWR_24 = Integer.fromInt(TWO_PWR_24_DBL) +const TWO_PWR_24 = Integer.fromInt(TWO_PWR_24_DBL) /** * Cast value to Integer type. diff --git a/packages/core/src/internal/bookmarks.ts b/packages/core/src/internal/bookmarks.ts index dd9dc3cb8..21885aad3 100644 --- a/packages/core/src/internal/bookmarks.ts +++ b/packages/core/src/internal/bookmarks.ts @@ -22,17 +22,17 @@ import * as util from './util' const BOOKMARKS_KEY = 'bookmarks' export class Bookmarks { - private _values: string[] + private readonly _values: string[] /** * @constructor * @param {string|string[]} values single bookmark as string or multiple bookmarks as a string array. */ - constructor(values?: string | string[] | Array | null) { + constructor (values?: string | string[] | string[] | null) { this._values = asStringArray(values) } - static empty(): Bookmarks { + static empty (): Bookmarks { return EMPTY_BOOKMARK } @@ -40,7 +40,7 @@ export class Bookmarks { * Check if the given Bookmarks holder is meaningful and can be send to the database. * @return {boolean} returns `true` bookmarks has a value, `false` otherwise. */ - isEmpty(): boolean { + isEmpty (): boolean { return this._values.length === 0 } @@ -48,7 +48,7 @@ export class Bookmarks { * Get all bookmarks values as an array. * @return {string[]} all values. */ - values(): string[] { + values (): string[] { return this._values } @@ -56,7 +56,7 @@ export class Bookmarks { * Get these bookmarks as an object for begin transaction call. * @return {Object} the value of this bookmarks holder as object. */ - asBeginTransactionParameters(): { [BOOKMARKS_KEY]?: string[] } { + asBeginTransactionParameters (): { [BOOKMARKS_KEY]?: string[] } { if (this.isEmpty()) { return {} } @@ -78,10 +78,10 @@ const EMPTY_BOOKMARK = new Bookmarks(null) * @param {string|string[]|Array} [value=undefined] argument to convert. * @return {string[]} value converted to an array. */ -function asStringArray( - value?: string | string[] | Array | null +function asStringArray ( + value?: string | string[] | string[] | null ): string[] { - if (!value) { + if (value == null) { return [] } @@ -98,6 +98,7 @@ function asStringArray( if (element !== undefined && element !== null) { if (!util.isString(element)) { throw new TypeError( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `Bookmark value should be a string, given: '${element}'` ) } @@ -108,6 +109,7 @@ function asStringArray( } throw new TypeError( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `Bookmarks should either be a string or a string array, given: '${value}'` ) } @@ -118,7 +120,7 @@ function asStringArray( * * @param {Array} value */ -function flattenArray(values: any[]): string[] { +function flattenArray (values: any[]): string[] { return values.reduce( (dest, value) => Array.isArray(value) diff --git a/packages/core/src/internal/connection-holder.ts b/packages/core/src/internal/connection-holder.ts index e9e7471c9..57217cf58 100644 --- a/packages/core/src/internal/connection-holder.ts +++ b/packages/core/src/internal/connection-holder.ts @@ -16,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable @typescript-eslint/promise-function-async */ import { newError } from '../error' import { assertString } from './util' @@ -23,7 +24,6 @@ import Connection from '../connection' import { ACCESS_MODE_WRITE } from './constants' import { Bookmarks } from './bookmarks' import ConnectionProvider from '../connection-provider' -import { Point } from '..' /** * @private @@ -33,42 +33,42 @@ interface ConnectionHolderInterface { * Returns the assigned access mode. * @returns {string} access mode */ - mode(): string | undefined + mode: () => string | undefined /** * Returns the target database name * @returns {string} the database name */ - database(): string | undefined + database: () => string | undefined /** * Returns the bookmarks */ - bookmarks(): Bookmarks + bookmarks: () => Bookmarks /** * Make this holder initialize new connection if none exists already. * @return {boolean} */ - initializeConnection(): boolean + initializeConnection: () => boolean /** * Get the current connection promise. * @return {Promise} promise resolved with the current connection. */ - getConnection(): Promise + getConnection: () => Promise /** * Notify this holder that single party does not require current connection any more. * @return {Promise} promise resolved with the current connection, never a rejected promise. */ - releaseConnection(): Promise + releaseConnection: () => Promise /** * Closes this holder and releases current connection (if any) despite any existing users. * @return {Promise} promise resolved when current connection is released to the pool. */ - close(): Promise + close: () => Promise } /** @@ -76,14 +76,14 @@ interface ConnectionHolderInterface { * @private */ class ConnectionHolder implements ConnectionHolderInterface { - private _mode: string + private readonly _mode: string private _database?: string - private _bookmarks: Bookmarks - private _connectionProvider?: ConnectionProvider + private readonly _bookmarks: Bookmarks + private readonly _connectionProvider?: ConnectionProvider private _referenceCount: number - private _connectionPromise: Promise - private _impersonatedUser?: string - private _onDatabaseNameResolved?: (databaseName?: string) => void + private _connectionPromise: Promise + private readonly _impersonatedUser?: string + private readonly _onDatabaseNameResolved?: (databaseName?: string) => void /** * @constructor @@ -95,7 +95,7 @@ class ConnectionHolder implements ConnectionHolderInterface { * @property {string?} params.impersonatedUser - the user which will be impersonated * @property {function(databaseName:string)} params.onDatabaseNameResolved - callback called when the database name is resolved */ - constructor({ + constructor ({ mode = ACCESS_MODE_WRITE, database = '', bookmarks, @@ -106,46 +106,46 @@ class ConnectionHolder implements ConnectionHolderInterface { mode?: string database?: string bookmarks?: Bookmarks - connectionProvider?: ConnectionProvider, - impersonatedUser?: string, + connectionProvider?: ConnectionProvider + impersonatedUser?: string onDatabaseNameResolved?: (databaseName?: string) => void } = {}) { this._mode = mode - this._database = database ? assertString(database, 'database') : '' - this._bookmarks = bookmarks || Bookmarks.empty() + this._database = database != null ? assertString(database, 'database') : '' + this._bookmarks = bookmarks ?? Bookmarks.empty() this._connectionProvider = connectionProvider this._impersonatedUser = impersonatedUser this._referenceCount = 0 - this._connectionPromise = Promise.resolve() + this._connectionPromise = Promise.resolve(null) this._onDatabaseNameResolved = onDatabaseNameResolved } - mode(): string | undefined { + mode (): string | undefined { return this._mode } - database(): string | undefined { + database (): string | undefined { return this._database } - setDatabase(database?: string) { + setDatabase (database?: string): void { this._database = database } - bookmarks(): Bookmarks { + bookmarks (): Bookmarks { return this._bookmarks } - connectionProvider(): ConnectionProvider | undefined { + connectionProvider (): ConnectionProvider | undefined { return this._connectionProvider } - referenceCount(): number { + referenceCount (): number { return this._referenceCount } - initializeConnection(): boolean { - if (this._referenceCount === 0 && this._connectionProvider) { + initializeConnection (): boolean { + if (this._referenceCount === 0 && (this._connectionProvider != null)) { this._connectionPromise = this._connectionProvider.acquireConnection({ accessMode: this._mode, database: this._database, @@ -160,11 +160,12 @@ class ConnectionHolder implements ConnectionHolderInterface { this._referenceCount++ return true } - getConnection(): Promise { + + getConnection (): Promise { return this._connectionPromise } - releaseConnection(): Promise { + releaseConnection (): Promise { if (this._referenceCount === 0) { return this._connectionPromise } @@ -177,7 +178,7 @@ class ConnectionHolder implements ConnectionHolderInterface { return this._connectionPromise } - close(): Promise { + close (): Promise { if (this._referenceCount === 0) { return this._connectionPromise } @@ -192,19 +193,19 @@ class ConnectionHolder implements ConnectionHolderInterface { * @return {Promise} - promise resolved then connection is returned to the pool. * @private */ - private _releaseConnection(): Promise { + private _releaseConnection (): Promise { this._connectionPromise = this._connectionPromise - .then((connection?: Connection|void) => { - if (connection) { + .then((connection?: Connection|null) => { + if (connection != null) { if (connection.isOpen()) { return connection .resetAndFlush() .catch(ignoreError) - .then(() => connection._release()) + .then(() => connection._release().then(() => null)) } - return connection._release() + return connection._release().then(() => null) } else { - return Promise.resolve() + return Promise.resolve(null) } }) .catch(ignoreError) @@ -218,13 +219,13 @@ class ConnectionHolder implements ConnectionHolderInterface { * releasing or initilizing */ export default class ReadOnlyConnectionHolder extends ConnectionHolder { - private _connectionHolder: ConnectionHolder + private readonly _connectionHolder: ConnectionHolder /** * Contructor * @param {ConnectionHolder} connectionHolder the connection holder which will treat the requests */ - constructor(connectionHolder: ConnectionHolder) { + constructor (connectionHolder: ConnectionHolder) { super({ mode: connectionHolder.mode(), database: connectionHolder.database(), @@ -239,7 +240,7 @@ export default class ReadOnlyConnectionHolder extends ConnectionHolder { * * @return {boolean} */ - initializeConnection(): boolean { + initializeConnection (): boolean { if (this._connectionHolder.referenceCount() === 0) { return false } @@ -250,7 +251,7 @@ export default class ReadOnlyConnectionHolder extends ConnectionHolder { * Get the current connection promise. * @return {Promise} promise resolved with the current connection. */ - getConnection(): Promise { + getConnection (): Promise { return this._connectionHolder.getConnection() } @@ -258,45 +259,45 @@ export default class ReadOnlyConnectionHolder extends ConnectionHolder { * Get the current connection promise, doesn't performs the release * @return {Promise} promise with the resolved current connection */ - releaseConnection(): Promise { - return this._connectionHolder.getConnection().catch(() => Promise.resolve()) + releaseConnection (): Promise { + return this._connectionHolder.getConnection().catch(() => Promise.resolve(null)) } /** * Get the current connection promise, doesn't performs the connection close * @return {Promise} promise with the resolved current connection */ - close(): Promise { - return this._connectionHolder.getConnection().catch(() => Promise.resolve()) + close (): Promise { + return this._connectionHolder.getConnection().catch(() => Promise.resolve(null)) } } class EmptyConnectionHolder extends ConnectionHolder { - mode(): undefined { + mode (): undefined { return undefined } - database(): undefined { + database (): undefined { return undefined } - initializeConnection() { + initializeConnection (): boolean { // nothing to initialize return true } - getConnection(): Promise { - return Promise.reject( + async getConnection (): Promise { + return await Promise.reject( newError('This connection holder does not serve connections') ) } - releaseConnection(): Promise { - return Promise.resolve() + async releaseConnection (): Promise { + return await Promise.resolve(null) } - close(): Promise { - return Promise.resolve() + async close (): Promise { + return await Promise.resolve(null) } } @@ -307,7 +308,9 @@ class EmptyConnectionHolder extends ConnectionHolder { */ const EMPTY_CONNECTION_HOLDER: EmptyConnectionHolder = new EmptyConnectionHolder() -// eslint-disable-next-line handle-callback-err -function ignoreError(error: Error) { } +// eslint-disable-next-line node/handle-callback-err +function ignoreError (error: Error): null { + return null +} export { ConnectionHolder, ReadOnlyConnectionHolder, EMPTY_CONNECTION_HOLDER } diff --git a/packages/core/src/internal/logger.ts b/packages/core/src/internal/logger.ts index 5b1bbc1d6..002643299 100644 --- a/packages/core/src/internal/logger.ts +++ b/packages/core/src/internal/logger.ts @@ -44,7 +44,7 @@ export class Logger { * @param {string} level the enabled logging level. * @param {function(level: string, message: string)} loggerFunction the function to write the log level and message. */ - constructor(level: LogLevel, loggerFunction: LoggerFunction) { + constructor (level: LogLevel, loggerFunction: LoggerFunction) { this._level = level this._loggerFunction = loggerFunction } @@ -54,8 +54,8 @@ export class Logger { * @param {Object} driverConfig the driver configuration as supplied by the user. * @return {Logger} a new logger instance or a no-op logger when not configured. */ - static create(driverConfig: { logging?: LoggingConfig }): Logger { - if (driverConfig && driverConfig.logging) { + static create (driverConfig: { logging?: LoggingConfig }): Logger { + if (driverConfig?.logging != null) { const loggingConfig = driverConfig.logging const level = extractConfiguredLevel(loggingConfig) const loggerFunction = extractConfiguredLogger(loggingConfig) @@ -68,7 +68,7 @@ export class Logger { * Create a no-op logger implementation. * @return {Logger} the no-op logger implementation. */ - static noOp(): Logger { + static noOp (): Logger { return noOpLogger } @@ -76,7 +76,7 @@ export class Logger { * Check if error logging is enabled, i.e. it is not a no-op implementation. * @return {boolean} `true` when enabled, `false` otherwise. */ - isErrorEnabled(): boolean { + isErrorEnabled (): boolean { return isLevelEnabled(this._level, ERROR) } @@ -84,7 +84,7 @@ export class Logger { * Log an error message. * @param {string} message the message to log. */ - error(message: string) { + error (message: string): void { if (this.isErrorEnabled()) { this._loggerFunction(ERROR, message) } @@ -94,7 +94,7 @@ export class Logger { * Check if warn logging is enabled, i.e. it is not a no-op implementation. * @return {boolean} `true` when enabled, `false` otherwise. */ - isWarnEnabled(): boolean { + isWarnEnabled (): boolean { return isLevelEnabled(this._level, WARN) } @@ -102,7 +102,7 @@ export class Logger { * Log an warning message. * @param {string} message the message to log. */ - warn(message: string) { + warn (message: string): void { if (this.isWarnEnabled()) { this._loggerFunction(WARN, message) } @@ -112,7 +112,7 @@ export class Logger { * Check if info logging is enabled, i.e. it is not a no-op implementation. * @return {boolean} `true` when enabled, `false` otherwise. */ - isInfoEnabled(): boolean { + isInfoEnabled (): boolean { return isLevelEnabled(this._level, INFO) } @@ -120,7 +120,7 @@ export class Logger { * Log an info message. * @param {string} message the message to log. */ - info(message: string) { + info (message: string): void { if (this.isInfoEnabled()) { this._loggerFunction(INFO, message) } @@ -130,7 +130,7 @@ export class Logger { * Check if debug logging is enabled, i.e. it is not a no-op implementation. * @return {boolean} `true` when enabled, `false` otherwise. */ - isDebugEnabled(): boolean { + isDebugEnabled (): boolean { return isLevelEnabled(this._level, DEBUG) } @@ -138,7 +138,7 @@ export class Logger { * Log a debug message. * @param {string} message the message to log. */ - debug(message: string) { + debug (message: string): void { if (this.isDebugEnabled()) { this._loggerFunction(DEBUG, message) } @@ -146,33 +146,33 @@ export class Logger { } class NoOpLogger extends Logger { - constructor() { + constructor () { super(INFO, (level: LogLevel, message: string) => {}) } - isErrorEnabled() { + isErrorEnabled (): boolean { return false } - error(message: string) {} + error (message: string): void {} - isWarnEnabled() { + isWarnEnabled (): boolean { return false } - warn(message: string) {} + warn (message: string): void {} - isInfoEnabled() { + isInfoEnabled (): boolean { return false } - info(message: string) {} + info (message: string): void {} - isDebugEnabled() { + isDebugEnabled (): boolean { return false } - debug(message: string) {} + debug (message: string): void {} } const noOpLogger = new NoOpLogger() @@ -183,7 +183,7 @@ const noOpLogger = new NoOpLogger() * @param {string} targetLevel the level to check. * @return {boolean} value of `true` when enabled, `false` otherwise. */ -function isLevelEnabled(configuredLevel: LogLevel, targetLevel: LogLevel) { +function isLevelEnabled (configuredLevel: LogLevel, targetLevel: LogLevel): boolean { return levels[configuredLevel] >= levels[targetLevel] } @@ -192,15 +192,15 @@ function isLevelEnabled(configuredLevel: LogLevel, targetLevel: LogLevel) { * @param {Object} loggingConfig the logging configuration. * @return {string} the configured log level or default when none configured. */ -function extractConfiguredLevel(loggingConfig: LoggingConfig): LogLevel { - if (loggingConfig && loggingConfig.level) { +function extractConfiguredLevel (loggingConfig: LoggingConfig): LogLevel { + if (loggingConfig?.level != null) { const configuredLevel = loggingConfig.level const value = levels[configuredLevel] - if (!value && value !== 0) { + if (value == null && value !== 0) { throw newError( `Illegal logging level: ${configuredLevel}. Supported levels are: ${Object.keys( levels - )}` + ).toString()}` ) } return configuredLevel @@ -213,12 +213,12 @@ function extractConfiguredLevel(loggingConfig: LoggingConfig): LogLevel { * @param {Object} loggingConfig the logging configuration. * @return {function(level: string, message: string)} the configured logging function. */ -function extractConfiguredLogger(loggingConfig: LoggingConfig): LoggerFunction { - if (loggingConfig && loggingConfig.logger) { +function extractConfiguredLogger (loggingConfig: LoggingConfig): LoggerFunction { + if (loggingConfig?.logger != null) { const configuredLogger = loggingConfig.logger - if (configuredLogger && typeof configuredLogger === 'function') { + if (configuredLogger != null && typeof configuredLogger === 'function') { return configuredLogger } } - throw newError(`Illegal logger function: ${loggingConfig.logger}`) + throw newError(`Illegal logger function: ${loggingConfig?.logger?.toString() ?? 'undefined'}`) } diff --git a/packages/core/src/internal/observers.ts b/packages/core/src/internal/observers.ts index 5ed50a962..6deafc357 100644 --- a/packages/core/src/internal/observers.ts +++ b/packages/core/src/internal/observers.ts @@ -76,7 +76,7 @@ export interface ResultStreamObserver extends StreamObserver { /** * Cancel pending record stream */ - cancel(): void + cancel: () => void /** * Pause the record consuming @@ -84,14 +84,14 @@ export interface ResultStreamObserver extends StreamObserver { * This function will supend the record consuming. It will not cancel the stream and the already * requested records will be sent to the subscriber. */ - pause(): void + pause: () => void /** * Resume the record consuming * * This function will resume the record consuming fetching more records from the server. */ - resume(): void + resume: () => void /** * Stream observer defaults to handling responses for two messages: RUN + PULL_ALL or RUN + DISCARD_ALL. @@ -103,12 +103,12 @@ export interface ResultStreamObserver extends StreamObserver { * * This function prepares the observer to only handle a single response message. */ - prepareToHandleSingleResponse(): void + prepareToHandleSingleResponse: () => void /** * Mark this observer as if it has completed with no metadata. */ - markCompleted(): void + markCompleted: () => void /** * Subscribe to events with provided observer. @@ -118,47 +118,48 @@ export interface ResultStreamObserver extends StreamObserver { * @param {function(metadata: Object)} observer.onCompleted - Handle stream tail, the metadata. * @param {function(error: Object)} observer.onError - Handle errors, should always be provided. */ - subscribe(observer: ResultObserver): void + subscribe: (observer: ResultObserver) => void } export class CompletedObserver implements ResultStreamObserver { - subscribe(observer: ResultObserver): void { + subscribe (observer: ResultObserver): void { apply(observer, observer.onKeys, []) apply(observer, observer.onCompleted, {}) } - cancel(): void { + cancel (): void { // do nothing } - pause(): void { + pause (): void { // do nothing } - resume(): void { + resume (): void { // do nothing } - prepareToHandleSingleResponse(): void { + prepareToHandleSingleResponse (): void { // do nothing } - markCompleted(): void { + markCompleted (): void { // do nothing } - onError(error: Error): void { + // eslint-disable-next-line node/handle-callback-err + onError (error: Error): void { // nothing to do, already finished throw Error('CompletedObserver not supposed to call onError') } } export class FailedObserver implements ResultStreamObserver { - private _error: Error - private _beforeError?: (error: Error) => void - private _observers: ResultObserver[] + private readonly _error: Error + private readonly _beforeError?: (error: Error) => void + private readonly _observers: ResultObserver[] - constructor({ + constructor ({ error, onError }: { @@ -171,41 +172,39 @@ export class FailedObserver implements ResultStreamObserver { this.onError(error) } - subscribe(observer: ResultObserver): void { + subscribe (observer: ResultObserver): void { apply(observer, observer.onError, this._error) this._observers.push(observer) } - onError(error: Error): void { - Promise.resolve(apply(this, this._beforeError, error)).then(() => - this._observers.forEach(o => apply(o, o.onError, error)) - ) + onError (error: Error): void { + apply(this, this._beforeError, error) + this._observers.forEach(o => apply(o, o.onError, error)) } - cancel(): void { + cancel (): void { // do nothing } - pause(): void { + pause (): void { // do nothing } - resume(): void { + resume (): void { // do nothing } - markCompleted(): void { + markCompleted (): void { // do nothing } - prepareToHandleSingleResponse(): void { + prepareToHandleSingleResponse (): void { // do nothing } - } -function apply(thisArg: any, func?: (param: T) => void, param?: T): void { - if (func) { +function apply (thisArg: any, func?: (param: T) => void, param?: T): void { + if (func != null) { func.bind(thisArg)(param as any) } } diff --git a/packages/core/src/internal/resolver/base-host-name-resolver.ts b/packages/core/src/internal/resolver/base-host-name-resolver.ts index 6289f4be3..d8ef2ef39 100644 --- a/packages/core/src/internal/resolver/base-host-name-resolver.ts +++ b/packages/core/src/internal/resolver/base-host-name-resolver.ts @@ -16,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable @typescript-eslint/promise-function-async */ import { ServerAddress } from '../server-address' diff --git a/packages/core/src/internal/resolver/configured-custom-resolver.ts b/packages/core/src/internal/resolver/configured-custom-resolver.ts index c61266e4f..ad436a921 100644 --- a/packages/core/src/internal/resolver/configured-custom-resolver.ts +++ b/packages/core/src/internal/resolver/configured-custom-resolver.ts @@ -16,26 +16,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable @typescript-eslint/promise-function-async */ import { ServerAddress } from '../server-address' -function resolveToSelf(address: ServerAddress) { +function resolveToSelf (address: ServerAddress): Promise { return Promise.resolve([address]) } export default class ConfiguredCustomResolver { private readonly _resolverFunction: (address: string) => string - constructor(resolverFunction: (address: string) => string) { - this._resolverFunction = resolverFunction || resolveToSelf + constructor (resolverFunction: (address: string) => string) { + this._resolverFunction = resolverFunction ?? resolveToSelf } - resolve(seedRouter: ServerAddress): Promise { + resolve (seedRouter: ServerAddress): Promise { return new Promise(resolve => resolve(this._resolverFunction(seedRouter.asHostPort())) ).then(resolved => { if (!Array.isArray(resolved)) { throw new TypeError( 'Configured resolver function should either return an array of addresses or a Promise resolved with an array of addresses.' + + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `Each address is ':'. Got: ${resolved}` ) } diff --git a/packages/core/src/internal/server-address.ts b/packages/core/src/internal/server-address.ts index 6721642ca..2e6716524 100644 --- a/packages/core/src/internal/server-address.ts +++ b/packages/core/src/internal/server-address.ts @@ -26,48 +26,48 @@ export class ServerAddress { private readonly _hostPort: string private readonly _stringValue: string - constructor( + constructor ( host: string, resolved: string | null | undefined, port: number, hostPort: string ) { this._host = assertString(host, 'host') - this._resolved = resolved ? assertString(resolved, 'resolved') : null + this._resolved = resolved != null ? assertString(resolved, 'resolved') : null this._port = assertNumber(port, 'port') this._hostPort = hostPort - this._stringValue = resolved ? `${hostPort}(${resolved})` : `${hostPort}` + this._stringValue = resolved != null ? `${hostPort}(${resolved})` : `${hostPort}` } - host() { + host (): string { return this._host } - resolvedHost() { - return this._resolved ? this._resolved : this._host + resolvedHost (): string { + return this._resolved != null ? this._resolved : this._host } - port() { + port (): number { return this._port } - resolveWith(resolved: string) { + resolveWith (resolved: string): ServerAddress { return new ServerAddress(this._host, resolved, this._port, this._hostPort) } - asHostPort() { + asHostPort (): string { return this._hostPort } - asKey() { + asKey (): string { return this._hostPort } - toString() { + toString (): string { return this._stringValue } - static fromUrl(url: string) { + static fromUrl (url: string): ServerAddress { const urlParsed = urlUtil.parseDatabaseUrl(url) return new ServerAddress( urlParsed.host, diff --git a/packages/core/src/internal/temporal-util.ts b/packages/core/src/internal/temporal-util.ts index ba0057d61..7598d237e 100644 --- a/packages/core/src/internal/temporal-util.ts +++ b/packages/core/src/internal/temporal-util.ts @@ -45,7 +45,7 @@ class ValueRange { this._maxInteger = int(max) } - contains (value: number | Integer | bigint) { + contains (value: number | Integer | bigint): boolean { if (isInt(value) && value instanceof Integer) { return ( value.greaterThanOrEqual(this._minInteger) && @@ -62,7 +62,7 @@ class ValueRange { } } - toString () { + toString (): string { return `[${this._minNumber}, ${this._maxNumber}]` } } @@ -271,7 +271,7 @@ export function timeZoneOffsetToIsoString ( const secondsValue = offsetSeconds.modulo(SECONDS_PER_MINUTE) const seconds = secondsValue.equals(0) ? null : formatNumber(secondsValue, 2) - return seconds + return seconds != null ? `${signPrefix}${hours}:${minutes}:${seconds}` : `${signPrefix}${hours}:${minutes}` } @@ -309,7 +309,7 @@ export function dateToIsoString ( * @param {string} isoString The iso date string * @returns {Date} the date */ - export function isoStringToStandardDate(isoString: string): Date { +export function isoStringToStandardDate (isoString: string): Date { return new Date(isoString) } @@ -323,7 +323,7 @@ export function totalNanoseconds ( standardDate: Date, nanoseconds?: NumberOrInteger ): NumberOrInteger { - nanoseconds = nanoseconds || 0 + nanoseconds = nanoseconds ?? 0 const nanosFromMillis = standardDate.getMilliseconds() * NANOS_PER_MILLISECOND return add(nanoseconds, nanosFromMillis) } @@ -432,7 +432,7 @@ function assertValidTemporalValue ( assertNumberOrInteger(value, name) if (!range.contains(value)) { throw newError( - `${name} is expected to be in range ${range} but was: ${value}` + `${name} is expected to be in range ${range.toString()} but was: ${value.toString()}` ) } return value @@ -554,7 +554,7 @@ function formatSecondsAndNanosecondsForDuration ( } } - return nanosecondsString ? secondsString + nanosecondsString : secondsString + return nanosecondsString != null ? secondsString + nanosecondsString : secondsString } /** @@ -582,7 +582,7 @@ function formatNumber ( } let numString = num.toString() - if (stringLength) { + if (stringLength != null) { // left pad the string with zeroes while (numString.length < stringLength) { numString = '0' + numString diff --git a/packages/core/src/internal/transaction-executor.ts b/packages/core/src/internal/transaction-executor.ts index 8051d764b..1d7677e87 100644 --- a/packages/core/src/internal/transaction-executor.ts +++ b/packages/core/src/internal/transaction-executor.ts @@ -16,12 +16,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable @typescript-eslint/promise-function-async */ import { newError, isRetriableError } from '../error' import Transaction from '../transaction' import TransactionPromise from '../transaction-promise' - const DEFAULT_MAX_RETRY_TIME_MS = 30 * 1000 // 30 seconds const DEFAULT_INITIAL_RETRY_DELAY_MS = 1000 // 1 seconds const DEFAULT_RETRY_DELAY_MULTIPLIER = 2.0 @@ -34,13 +34,13 @@ type Reject = (value: any) => void type Timeout = ReturnType export class TransactionExecutor { - private _maxRetryTimeMs: number - private _initialRetryDelayMs: number - private _multiplier: number - private _jitterFactor: number + private readonly _maxRetryTimeMs: number + private readonly _initialRetryDelayMs: number + private readonly _multiplier: number + private readonly _jitterFactor: number private _inFlightTimeoutIds: Timeout[] - constructor( + constructor ( maxRetryTimeMs?: number | null, initialRetryDelayMs?: number, multiplier?: number, @@ -80,7 +80,7 @@ export class TransactionExecutor { resolve, reject, transactionWrapper - ) + ).catch(reject) }).catch(error => { const retryStartTimeMs = Date.now() const retryDelayMs = this._initialRetryDelayMs @@ -95,7 +95,7 @@ export class TransactionExecutor { }) } - close() { + close (): void { // cancel all existing timeouts to prevent further retries this._inFlightTimeoutIds.forEach(timeoutId => clearTimeout(timeoutId)) this._inFlightTimeoutIds = [] @@ -128,7 +128,7 @@ export class TransactionExecutor { resolve, reject, transactionWrapper - ) + ).catch(reject) }, nextRetryTime) // add newly created timeoutId to the list of all in-flight timeouts this._inFlightTimeoutIds.push(timeoutId) @@ -150,7 +150,7 @@ export class TransactionExecutor { transactionWork: TransactionWork, resolve: Resolve, reject: Reject, - transactionWrapper?: (tx: Transaction) => Tx, + transactionWrapper?: (tx: Transaction) => Tx ): Promise { let tx: Transaction try { @@ -164,7 +164,7 @@ export class TransactionExecutor { // The conversion from `tx` as `unknown` then to `Tx` is necessary // because it is not possible to be sure that `Tx` is a subtype of `Transaction` // in using static type checking. - const wrap = transactionWrapper || ((tx: Transaction) => tx as unknown as Tx) + const wrap = transactionWrapper ?? ((tx: Transaction) => tx as unknown as Tx) const wrappedTx = wrap(tx) const resultPromise = this._safeExecuteTransactionWork(wrappedTx, transactionWork) @@ -195,7 +195,7 @@ export class TransactionExecutor { tx: Transaction, resolve: Resolve, reject: Reject - ) { + ): void { if (tx.isOpen()) { // transaction work returned resolved promise and transaction has not been committed/rolled back // try to commit the transaction @@ -215,7 +215,7 @@ export class TransactionExecutor { } } - _handleTransactionWorkFailure(error: any, tx: Transaction, reject: Reject) { + _handleTransactionWorkFailure (error: any, tx: Transaction, reject: Reject): void { if (tx.isOpen()) { // transaction work failed and the transaction is still open, roll it back and propagate the failure tx.rollback() @@ -223,44 +223,45 @@ export class TransactionExecutor { // ignore the rollback error }) .then(() => reject(error)) // propagate the original error we got from the transaction work + .catch(reject) } else { // transaction is already rolled back, propagate the error reject(error) } } - _computeDelayWithJitter(delayMs: number): number { + _computeDelayWithJitter (delayMs: number): number { const jitter = delayMs * this._jitterFactor const min = delayMs - jitter const max = delayMs + jitter return Math.random() * (max - min) + min } - _verifyAfterConstruction() { + _verifyAfterConstruction (): void { if (this._maxRetryTimeMs < 0) { - throw newError('Max retry time should be >= 0: ' + this._maxRetryTimeMs) + throw newError('Max retry time should be >= 0: ' + this._maxRetryTimeMs.toString()) } if (this._initialRetryDelayMs < 0) { throw newError( - 'Initial retry delay should >= 0: ' + this._initialRetryDelayMs + 'Initial retry delay should >= 0: ' + this._initialRetryDelayMs.toString() ) } if (this._multiplier < 1.0) { - throw newError('Multiplier should be >= 1.0: ' + this._multiplier) + throw newError('Multiplier should be >= 1.0: ' + this._multiplier.toString()) } if (this._jitterFactor < 0 || this._jitterFactor > 1) { throw newError( - 'Jitter factor should be in [0.0, 1.0]: ' + this._jitterFactor + 'Jitter factor should be in [0.0, 1.0]: ' + this._jitterFactor.toFixed() ) } } } -function _valueOrDefault( +function _valueOrDefault ( value: number | undefined | null, defaultValue: number ): number { - if (value || value === 0) { + if (value != null) { return value } return defaultValue diff --git a/packages/core/src/internal/tx-config.ts b/packages/core/src/internal/tx-config.ts index cd6ac02c1..9c23b8e99 100644 --- a/packages/core/src/internal/tx-config.ts +++ b/packages/core/src/internal/tx-config.ts @@ -35,7 +35,7 @@ export class TxConfig { * @constructor * @param {Object} config the raw configuration object. */ - constructor(config: any) { + constructor (config: any) { assertValidConfig(config) this.timeout = extractTimeout(config) this.metadata = extractMetadata(config) @@ -45,7 +45,7 @@ export class TxConfig { * Get an empty config object. * @return {TxConfig} an empty config. */ - static empty(): TxConfig { + static empty (): TxConfig { return EMPTY_CONFIG } @@ -53,7 +53,7 @@ export class TxConfig { * Check if this config object is empty. I.e. has no configuration values specified. * @return {boolean} `true` if this object is empty, `false` otherwise. */ - isEmpty(): boolean { + isEmpty (): boolean { return Object.values(this).every(value => value == null) } } @@ -63,8 +63,8 @@ const EMPTY_CONFIG = new TxConfig({}) /** * @return {Integer|null} */ -function extractTimeout(config: any): Integer | null { - if (util.isObject(config) && (config.timeout || config.timeout === 0)) { +function extractTimeout (config: any): Integer | null { + if (util.isObject(config) && config.timeout != null) { util.assertNumberOrInteger(config.timeout, 'Transaction timeout') const timeout = int(config.timeout) if (timeout.isNegative()) { @@ -78,8 +78,8 @@ function extractTimeout(config: any): Integer | null { /** * @return {object|null} */ -function extractMetadata(config: any): any { - if (util.isObject(config) && config.metadata) { +function extractMetadata (config: any): any { + if (util.isObject(config) && config.metadata != null) { const metadata = config.metadata util.assertObject(metadata, 'config.metadata') if (Object.keys(metadata).length !== 0) { @@ -90,8 +90,8 @@ function extractMetadata(config: any): any { return null } -function assertValidConfig(config: any): void { - if (config) { +function assertValidConfig (config: any): void { + if (config != null) { util.assertObject(config, 'Transaction config') } } diff --git a/packages/core/src/internal/url-util.ts b/packages/core/src/internal/url-util.ts index ee3aea216..c2e292fae 100644 --- a/packages/core/src/internal/url-util.ts +++ b/packages/core/src/internal/url-util.ts @@ -30,7 +30,7 @@ class Url { readonly hostAndPort: string readonly query: Object - constructor( + constructor ( scheme: string | null, host: string, port: number, @@ -86,7 +86,7 @@ interface ParsedUri { path?: string } -function parseDatabaseUrl(url: string) { +function parseDatabaseUrl (url: string): Url { assertString(url, 'URL') const sanitized = sanitizeUrl(url) @@ -100,26 +100,26 @@ function parseDatabaseUrl(url: string) { const port = extractPort(parsedUrl.port, scheme) const hostAndPort = `${formattedHost}:${port}` const query = extractQuery( - // @ts-ignore - parsedUrl.query || extractResourceQueryString(parsedUrl.resourceName), + // @ts-expect-error + parsedUrl.query ?? extractResourceQueryString(parsedUrl.resourceName), url ) return new Url(scheme, host, port, hostAndPort, query) } -function extractResourceQueryString(resource?: string): string | null { +function extractResourceQueryString (resource?: string): string | null { if (typeof resource !== 'string') { return null } - const [_, query] = resource.split('?') + const [, query] = resource.split('?') return query } -function sanitizeUrl(url: string): { schemeMissing: boolean; url: string } { +function sanitizeUrl (url: string): { schemeMissing: boolean, url: string } { url = url.trim() - if (url.indexOf('://') === -1) { + if (!url.includes('://')) { // url does not contain scheme, add dummy 'none://' to make parser work correctly return { schemeMissing: true, url: `none://${url}` } } @@ -127,8 +127,8 @@ function sanitizeUrl(url: string): { schemeMissing: boolean; url: string } { return { schemeMissing: false, url: url } } -function extractScheme(scheme?: string): string | null { - if (scheme) { +function extractScheme (scheme?: string): string | null { + if (scheme != null) { scheme = scheme.trim() if (scheme.charAt(scheme.length - 1) === ':') { scheme = scheme.substring(0, scheme.length - 1) @@ -138,40 +138,40 @@ function extractScheme(scheme?: string): string | null { return null } -function extractHost(host?: string, url?: string): string { - if (!host) { - throw new Error(`Unable to extract host from ${url}`) +function extractHost (host?: string, url?: string): string { + if (host == null) { + throw new Error('Unable to extract host from null or undefined URL') } return host.trim() } -function extractPort( +function extractPort ( portString: string | number | undefined, scheme: string | null ): number { const port = typeof portString === 'string' ? parseInt(portString, 10) : portString - return port === 0 || port ? port : defaultPortForScheme(scheme) + return port != null ? port : defaultPortForScheme(scheme) } -function extractQuery( +function extractQuery ( queryString: string | undefined | null, url: string ): Object { - const query = queryString ? trimAndSanitizeQuery(queryString) : null + const query = queryString != null ? trimAndSanitizeQuery(queryString) : null const context: any = {} - if (query) { + if (query != null) { query.split('&').forEach((pair: string) => { const keyValue = pair.split('=') if (keyValue.length !== 2) { - throw new Error(`Invalid parameters: '${keyValue}' in URL '${url}'.`) + throw new Error(`Invalid parameters: '${keyValue.toString()}' in URL '${url}'.`) } const key = trimAndVerifyQueryElement(keyValue[0], 'key', url) const value = trimAndVerifyQueryElement(keyValue[1], 'value', url) - if (context[key]) { + if (context[key] !== undefined) { throw new Error( `Duplicated query parameters with key '${key}' in URL '${url}'` ) @@ -184,23 +184,23 @@ function extractQuery( return context } -function trimAndSanitizeQuery(query: string): string { - query = (query || '').trim() - if (query && query.charAt(0) === '?') { +function trimAndSanitizeQuery (query: string): string { + query = (query ?? '').trim() + if (query?.charAt(0) === '?') { query = query.substring(1, query.length) } return query } -function trimAndVerifyQueryElement(element: string, name: string, url: string) { - element = (element || '').trim() - if (!element) { +function trimAndVerifyQueryElement (element: string, name: string, url: string): string { + element = (element ?? '').trim() + if (element === '') { throw new Error(`Illegal empty ${name} in URL query '${url}'`) } return element } -function escapeIPv6Address(address: string) { +function escapeIPv6Address (address: string): string { const startsWithSquareBracket = address.charAt(0) === '[' const endsWithSquareBracket = address.charAt(address.length - 1) === ']' @@ -213,24 +213,24 @@ function escapeIPv6Address(address: string) { } } -function formatHost(host: string) { - if (!host) { +function formatHost (host: string): string { + if (host === '' || host == null) { throw new Error(`Illegal host ${host}`) } - const isIPv6Address = host.indexOf(':') >= 0 + const isIPv6Address = host.includes(':') return isIPv6Address ? escapeIPv6Address(host) : host } -function formatIPv4Address(address: string, port: number): string { +function formatIPv4Address (address: string, port: number): string { return `${address}:${port}` } -function formatIPv6Address(address: string, port: number): string { +function formatIPv6Address (address: string, port: number): string { const escapedAddress = escapeIPv6Address(address) return `${escapedAddress}:${port}` } -function defaultPortForScheme(scheme: string | null): number { +function defaultPortForScheme (scheme: string | null): number { if (scheme === 'http') { return DEFAULT_HTTP_PORT } else if (scheme === 'https') { @@ -240,22 +240,22 @@ function defaultPortForScheme(scheme: string | null): number { } } -function uriJsParse(value: string) { +function uriJsParse (value: string): ParsedUri { // JS version of Python partition function - function partition(s: string, delimiter: string): [string, string, string] { + function partition (s: string, delimiter: string): [string, string, string] { const i = s.indexOf(delimiter) if (i >= 0) return [s.substring(0, i), s[i], s.substring(i + 1)] else return [s, '', ''] } // JS version of Python rpartition function - function rpartition(s: string, delimiter: string): [string, string, string] { + function rpartition (s: string, delimiter: string): [string, string, string] { const i = s.lastIndexOf(delimiter) if (i >= 0) return [s.substring(0, i), s[i], s.substring(i + 1)] else return ['', '', s] } - function between( + function between ( s: string, ldelimiter: string, rdelimiter: string @@ -270,9 +270,9 @@ function uriJsParse(value: string) { // - userInfo (optional, might contain both user name and password) // - host // - port (optional, included only as a string) - function parseAuthority(value: string): ParsedUri { - let parsed: ParsedUri = {}, - parts: [string, string, string] + function parseAuthority (value: string): ParsedUri { + const parsed: ParsedUri = {} + let parts: [string, string, string] // Parse user info parts = rpartition(value, '@') @@ -282,7 +282,7 @@ function uriJsParse(value: string) { } // Parse host and port - const [ipv6Host, rest] = between(value, `[`, `]`) + const [ipv6Host, rest] = between(value, '[', ']') if (ipv6Host !== '') { parsed.host = ipv6Host parts = partition(rest, ':') @@ -298,8 +298,8 @@ function uriJsParse(value: string) { return parsed } - let parsed: ParsedUri = {}, - parts: string[] + let parsed: ParsedUri = {} + let parts: string[] // Parse scheme parts = partition(value, ':') diff --git a/packages/core/src/internal/util.ts b/packages/core/src/internal/util.ts index 509b2027c..f5d6bbbbf 100644 --- a/packages/core/src/internal/util.ts +++ b/packages/core/src/internal/util.ts @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +// eslint-disable-next-line @typescript-eslint/no-unused-vars import Integer, { isInt } from '../integer' import { NumberOrInteger } from '../graph-types' import { EncryptionLevel } from '../types' @@ -30,7 +30,7 @@ const ENCRYPTION_OFF: EncryptionLevel = 'ENCRYPTION_OFF' * @param obj The subject object * @returns {boolean} True if it's empty object or null */ -function isEmptyObjectOrNull(obj?: any): boolean { +function isEmptyObjectOrNull (obj?: any): boolean { if (obj === null) { return true } @@ -40,7 +40,7 @@ function isEmptyObjectOrNull(obj?: any): boolean { } for (const prop in obj) { - if (Object.prototype.hasOwnProperty.bind(obj, prop)) { + if (obj[prop] !== undefined) { return false } } @@ -53,7 +53,7 @@ function isEmptyObjectOrNull(obj?: any): boolean { * @param obj The subject * @returns {boolean} True if it's an object */ -function isObject(obj: any): boolean { +function isObject (obj: any): boolean { return typeof obj === 'object' && !Array.isArray(obj) && obj !== null } @@ -64,25 +64,25 @@ function isObject(obj: any): boolean { * @return {{validatedQuery: string|{text: string, parameters: Object}, params: Object}} the normalized query with parameters. * @throws TypeError when either given query or parameters are invalid. */ -function validateQueryAndParameters( - query: string | String | { text: string; parameters?: any }, +function validateQueryAndParameters ( + query: string | String | { text: string, parameters?: any }, parameters?: any, opt?: { skipAsserts: boolean } ): { - validatedQuery: string - params: any -} { + validatedQuery: string + params: any + } { let validatedQuery: string = '' - let params = parameters || {} - const skipAsserts: boolean = opt?.skipAsserts || false + let params = parameters ?? {} + const skipAsserts: boolean = opt?.skipAsserts ?? false if (typeof query === 'string') { validatedQuery = query } else if (query instanceof String) { validatedQuery = query.toString() - } else if (typeof query === 'object' && query.text) { + } else if (typeof query === 'object' && query.text != null) { validatedQuery = query.text - params = query.parameters || {} + params = query.parameters ?? {} } if (!skipAsserts) { @@ -100,7 +100,7 @@ function validateQueryAndParameters( * @returns {object} The subject object * @throws {TypeError} when the supplied param is not an object */ -function assertObject(obj: any, objName: string): Object { +function assertObject (obj: any, objName: string): Object { if (!isObject(obj)) { throw new TypeError( objName + ' expected to be an object but was: ' + stringify(obj) @@ -116,10 +116,10 @@ function assertObject(obj: any, objName: string): Object { * @returns {string} The subject string * @throws {TypeError} when the supplied param is not a string */ -function assertString(obj: any, objName: Object): string { +function assertString (obj: any, objName: Object): string { if (!isString(obj)) { throw new TypeError( - objName + ' expected to be string but was: ' + stringify(obj) + stringify(objName) + ' expected to be string but was: ' + stringify(obj) ) } return obj @@ -132,7 +132,7 @@ function assertString(obj: any, objName: Object): string { * @returns {number} The number * @throws {TypeError} when the supplied param is not a number */ -function assertNumber(obj: any, objName: string): number { +function assertNumber (obj: any, objName: string): number { if (typeof obj !== 'number') { throw new TypeError( objName + ' expected to be a number but was: ' + stringify(obj) @@ -148,7 +148,7 @@ function assertNumber(obj: any, objName: string): number { * @returns {number|Integer} The subject object * @throws {TypeError} when the supplied param is not a number or integer */ -function assertNumberOrInteger(obj: any, objName: string): NumberOrInteger { +function assertNumberOrInteger (obj: any, objName: string): NumberOrInteger { if (typeof obj !== 'number' && typeof obj !== 'bigint' && !isInt(obj)) { throw new TypeError( objName + @@ -166,7 +166,7 @@ function assertNumberOrInteger(obj: any, objName: string): NumberOrInteger { * @returns {Date} The valida date * @throws {TypeError} when the supplied param is not a valid date */ -function assertValidDate(obj: any, objName: string): Date { +function assertValidDate (obj: any, objName: string): Date { if (Object.prototype.toString.call(obj) !== '[object Date]') { throw new TypeError( objName + @@ -190,7 +190,7 @@ function assertValidDate(obj: any, objName: string): Date { * @returns {void} * @throws {TypeError} if the query is not valid */ -function assertCypherQuery(obj: any): void { +function assertCypherQuery (obj: any): void { assertString(obj, 'Cypher query') if (obj.trim().length === 0) { throw new TypeError('Cypher query is expected to be a non-empty string.') @@ -203,12 +203,13 @@ function assertCypherQuery(obj: any): void { * @returns {void} * @throws {TypeError} if the parameters is not valid */ -function assertQueryParameters(obj: any): void { +function assertQueryParameters (obj: any): void { if (!isObject(obj)) { // objects created with `Object.create(null)` do not have a constructor property - const constructor = obj.constructor ? ' ' + obj.constructor.name : '' + // eslint-disable-next-line @typescript-eslint/restrict-plus-operands + const constructor = obj.constructor != null ? ' ' + obj.constructor.name : '' throw new TypeError( - `Query parameters are expected to either be undefined/null or an object, given:${constructor} ${obj}` + `Query parameters are expected to either be undefined/null or an object, given:${constructor} ${JSON.stringify(obj)}` ) } } @@ -219,7 +220,7 @@ function assertQueryParameters(obj: any): void { * @param str The string * @returns {boolean} True if the supplied object is an string */ -function isString(str: any): str is string { +function isString (str: any): str is string { return Object.prototype.toString.call(str) === '[object String]' } diff --git a/packages/core/src/json.ts b/packages/core/src/json.ts index a1eeebf91..1142d59c2 100644 --- a/packages/core/src/json.ts +++ b/packages/core/src/json.ts @@ -23,7 +23,7 @@ * @param val A JavaScript value, usually an object or array, to be converted. * @returns A JSON string representing the given value. */ -export function stringify (val: any) { +export function stringify (val: any): string { return JSON.stringify(val, (_, value) => typeof value === 'bigint' ? `${value}n` : value ) diff --git a/packages/core/src/record.ts b/packages/core/src/record.ts index 7df54286a..54042997f 100644 --- a/packages/core/src/record.ts +++ b/packages/core/src/record.ts @@ -38,7 +38,7 @@ function generateFieldLookup< Entries extends Dict = Dict, Key extends keyof Entries = keyof Entries, FieldLookup extends Dict = Dict ->(keys: Key[]): FieldLookup { +> (keys: Key[]): FieldLookup { const lookup: Dict = {} keys.forEach((name, idx) => { lookup[name as string] = idx @@ -72,8 +72,8 @@ class Record< > { keys: Key[] length: number - private _fields: any[] - private _fieldLookup: FieldLookup + private readonly _fields: any[] + private readonly _fieldLookup: FieldLookup /** * Create a new record object. @@ -85,7 +85,7 @@ class Record< * field names to values. If this is null, one will be * generated. */ - constructor(keys: Key[], fields: any[], fieldLookup?: FieldLookup) { + constructor (keys: Key[], fields: any[], fieldLookup?: FieldLookup) { /** * Field keys, in the order the fields appear in the record. * @type {string[]} @@ -97,7 +97,7 @@ class Record< */ this.length = keys.length this._fields = fields - this._fieldLookup = fieldLookup || generateFieldLookup(keys) + this._fieldLookup = fieldLookup ?? generateFieldLookup(keys) } /** @@ -108,7 +108,7 @@ class Record< * @param {function(value: Object, key: string, record: Record)} visitor the function to apply to each field. * @returns {void} Nothing */ - forEach(visitor: Visitor): void { + forEach (visitor: Visitor): void { for (const [key, value] of this.entries()) { visitor(value, key as Key, this) } @@ -141,7 +141,7 @@ class Record< * @generator * @returns {IterableIterator} */ - *entries(): IterableIterator<[string, any]> { + * entries (): IterableIterator<[string, any]> { for (let i = 0; i < this.keys.length; i++) { yield [this.keys[i] as string, this._fields[i]] } @@ -153,7 +153,7 @@ class Record< * @generator * @returns {IterableIterator} */ - *values(): IterableIterator { + * values (): IterableIterator { for (let i = 0; i < this.keys.length; i++) { yield this._fields[i] } @@ -165,7 +165,7 @@ class Record< * @generator * @returns {IterableIterator} */ - *[Symbol.iterator](): IterableIterator { + * [Symbol.iterator] (): IterableIterator { for (let i = 0; i < this.keys.length; i++) { yield this._fields[i] } @@ -176,7 +176,8 @@ class Record< * * @returns {Object} */ - toObject(): Entries { + toObject (): Entries { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions const obj: Entries = {} as Entries for (const [key, value] of this.entries()) { @@ -187,7 +188,7 @@ class Record< } get(key: K): Entries[K] - get(key: keyof FieldLookup | number): any + get (key: keyof FieldLookup | number): any /** * Get a value from this record, either by index or by field key. @@ -195,16 +196,16 @@ class Record< * @param {string|Number} key Field key, or the index of the field. * @returns {*} */ - get(key: string | number): any { + get (key: string | number): any { let index if (!(typeof key === 'number')) { - index = this._fieldLookup[key as string] + index = this._fieldLookup[key] if (index === undefined) { throw newError( "This record has no field with key '" + key + "', available key are: [" + - this.keys + + this.keys.toString() + '].' ) } @@ -215,7 +216,7 @@ class Record< if (index > this._fields.length - 1 || index < 0) { throw newError( "This record has no field with index '" + - index + + index.toString() + "'. Remember that indexes start at `0`, " + 'and make sure your query returns records in the shape you meant it to.' ) @@ -230,7 +231,7 @@ class Record< * @param {string|Number} key Field key, or the index of the field. * @returns {boolean} */ - has(key: Key | string | number): boolean { + has (key: Key | string | number): boolean { // if key is a number, we check if it is in the _fields array if (typeof key === 'number') { return key >= 0 && key < this._fields.length diff --git a/packages/core/src/result-summary.ts b/packages/core/src/result-summary.ts index d330d1abb..1431fefa2 100644 --- a/packages/core/src/result-summary.ts +++ b/packages/core/src/result-summary.ts @@ -25,7 +25,7 @@ import { NumberOrInteger } from './graph-types' * @access public */ class ResultSummary { - query: { text: string; parameters: { [key: string]: any } } + query: { text: string, parameters: { [key: string]: any } } queryType: string counters: QueryStatistics updateStatistics: QueryStatistics @@ -43,7 +43,7 @@ class ResultSummary { * @param {Object} metadata - Query metadata * @param {number|undefined} protocolVersion - Bolt Protocol Version */ - constructor( + constructor ( query: string, parameters: { [key: string]: any }, metadata: any, @@ -70,7 +70,7 @@ class ResultSummary { * @type {QueryStatistics} * @public */ - this.counters = new QueryStatistics(metadata.stats || {}) + this.counters = new QueryStatistics(metadata.stats ?? {}) // for backwards compatibility, remove in future version /** * Use {@link ResultSummary.counters} instead. @@ -87,8 +87,8 @@ class ResultSummary { * @public */ this.plan = - metadata.plan || metadata.profile - ? new Plan(metadata.plan || metadata.profile) + metadata.plan != null || metadata.profile != null + ? new Plan(metadata.plan ?? metadata.profile) : false /** @@ -98,7 +98,7 @@ class ResultSummary { * @type {ProfiledPlan} * @public */ - this.profile = metadata.profile ? new ProfiledPlan(metadata.profile) : false + this.profile = metadata.profile != null ? new ProfiledPlan(metadata.profile) : false /** * An array of notifications that might arise when executing the query. Notifications can be warnings about @@ -135,14 +135,14 @@ class ResultSummary { * @type {{name: string}} * @public */ - this.database = { name: metadata.db || null } + this.database = { name: metadata.db ?? null } } - _buildNotifications(notifications: any[]): Notification[] { - if (!notifications) { + _buildNotifications (notifications: any[]): Notification[] { + if (notifications == null) { return [] } - return notifications.map(function(n: any): Notification { + return notifications.map(function (n: any): Notification { return new Notification(n) }) } @@ -151,7 +151,7 @@ class ResultSummary { * Check if the result summary has a plan * @return {boolean} */ - hasPlan(): boolean { + hasPlan (): boolean { return this.plan instanceof Plan } @@ -159,7 +159,7 @@ class ResultSummary { * Check if the result summary has a profile * @return {boolean} */ - hasProfile(): boolean { + hasProfile (): boolean { return this.profile instanceof ProfiledPlan } } @@ -179,11 +179,11 @@ class Plan { * @constructor * @param {Object} plan - Object with plan data */ - constructor(plan: any) { + constructor (plan: any) { this.operatorType = plan.operatorType this.identifiers = plan.identifiers this.arguments = plan.args - this.children = plan.children + this.children = plan.children != null ? plan.children.map((child: any) => new Plan(child)) : [] } @@ -210,7 +210,7 @@ class ProfiledPlan { * @constructor * @param {Object} profile - Object with profile data */ - constructor(profile: any) { + constructor (profile: any) { this.operatorType = profile.operatorType this.identifiers = profile.identifiers this.arguments = profile.args @@ -220,12 +220,12 @@ class ProfiledPlan { this.pageCacheHits = valueOrDefault('pageCacheHits', profile) this.pageCacheHitRatio = valueOrDefault('pageCacheHitRatio', profile) this.time = valueOrDefault('time', profile) - this.children = profile.children + this.children = profile.children != null ? profile.children.map((child: any) => new ProfiledPlan(child)) : [] } - hasPageCacheStats(): boolean { + hasPageCacheStats (): boolean { return ( this.pageCacheMisses > 0 || this.pageCacheHits > 0 || @@ -256,7 +256,7 @@ class Stats { * @constructor * @private */ - constructor() { + constructor () { /** * nodes created * @type {number} @@ -341,7 +341,7 @@ class QueryStatistics { * @constructor * @param {Object} statistics - Result statistics */ - constructor(statistics: any) { + constructor (statistics: any) { this._stats = { nodesCreated: 0, nodesDeleted: 0, @@ -353,7 +353,7 @@ class QueryStatistics { indexesAdded: 0, indexesRemoved: 0, constraintsAdded: 0, - constraintsRemoved: 0, + constraintsRemoved: 0 } this._systemUpdates = 0 Object.keys(statistics).forEach(index => { @@ -377,20 +377,21 @@ class QueryStatistics { * Did the database get updated? * @return {boolean} */ - containsUpdates(): boolean { - return this._containsUpdates !== undefined ? - this._containsUpdates : ( - Object.keys(this._stats).reduce((last, current) => { - return last + this._stats[current] - }, 0) > 0 - ) + containsUpdates (): boolean { + return this._containsUpdates !== undefined + ? this._containsUpdates + : ( + Object.keys(this._stats).reduce((last, current) => { + return last + this._stats[current] + }, 0) > 0 + ) } /** * Returns the query statistics updates in a dictionary. * @returns {Stats} */ - updates(): Stats { + updates (): Stats { return this._stats } @@ -398,23 +399,24 @@ class QueryStatistics { * Return true if the system database get updated, otherwise false * @returns {boolean} - If the system database get updated or not. */ - containsSystemUpdates(): boolean { - return this._containsSystemUpdates !== undefined ? - this._containsSystemUpdates : this._systemUpdates > 0 + containsSystemUpdates (): boolean { + return this._containsSystemUpdates !== undefined + ? this._containsSystemUpdates + : this._systemUpdates > 0 } /** * @returns {number} - Number of system updates */ - systemUpdates(): number { + systemUpdates (): number { return this._systemUpdates } } interface NotificationPosition { - offset: number - line: number - column: number + offset?: number + line?: number + column?: number } /** @@ -433,7 +435,7 @@ class Notification { * @constructor * @param {Object} notification - Object with notification data */ - constructor(notification: any) { + constructor (notification: any) { this.code = notification.code this.title = notification.title this.description = notification.description @@ -441,15 +443,17 @@ class Notification { this.position = Notification._constructPosition(notification.position) } - static _constructPosition(pos: NotificationPosition) { - if (!pos) { + static _constructPosition (pos: NotificationPosition): NotificationPosition { + if (pos == null) { return {} } + /* eslint-disable @typescript-eslint/no-non-null-assertion */ return { - offset: intValue(pos.offset), - line: intValue(pos.line), - column: intValue(pos.column) + offset: intValue(pos.offset!), + line: intValue(pos.line!), + column: intValue(pos.column!) } + /* eslint-enable @typescript-eslint/no-non-null-assertion */ } } @@ -469,8 +473,8 @@ class ServerInfo { * @param {Object} connectionInfo - Bolt connection info * @param {number} protocolVersion - Bolt Protocol Version */ - constructor(serverMeta?: any, protocolVersion?: number) { - if (serverMeta) { + constructor (serverMeta?: any, protocolVersion?: number) { + if (serverMeta != null) { /** * The server adress * @type {string} @@ -495,22 +499,22 @@ class ServerInfo { } } -function intValue(value: NumberOrInteger): number { +function intValue (value: NumberOrInteger): number { if (value instanceof Integer) { return value.toInt() - } else if (typeof value == 'bigint') { + } else if (typeof value === 'bigint') { return int(value).toInt() } else { return value } } -function valueOrDefault( +function valueOrDefault ( key: string, - values: { [key: string]: NumberOrInteger }, + values: { [key: string]: NumberOrInteger } | false, defaultValue: number = 0 ): number { - if (key in values) { + if (values !== false && key in values) { const value = values[key] return intValue(value) } else { @@ -539,7 +543,7 @@ export { Stats } export type { - NotificationPosition, + NotificationPosition } export default ResultSummary diff --git a/packages/core/src/result.ts b/packages/core/src/result.ts index 729168be9..fa4a28e1c 100644 --- a/packages/core/src/result.ts +++ b/packages/core/src/result.ts @@ -17,11 +17,14 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/promise-function-async */ + import ResultSummary from './result-summary' import Record from './record' import { Query, PeekableAsyncIterator } from './types' import { observer, util, connectionHolder } from './internal' -import { newError } from './error' +import { newError, PROTOCOL_ERROR } from './error' +import { NumberOrInteger } from './graph-types' const { EMPTY_CONNECTION_HOLDER } = connectionHolder @@ -30,7 +33,8 @@ const { EMPTY_CONNECTION_HOLDER } = connectionHolder * @param {Error} error The error * @returns {void} */ -const DEFAULT_ON_ERROR = (error: Error) => { +const DEFAULT_ON_ERROR = (error: Error): void => { + // eslint-disable-next-line @typescript-eslint/restrict-plus-operands, @typescript-eslint/no-base-to-string console.log('Uncaught error when processing result: ' + error) } @@ -39,14 +43,14 @@ const DEFAULT_ON_ERROR = (error: Error) => { * @param {ResultSummary} summary * @returns {void} */ -const DEFAULT_ON_COMPLETED = (summary: ResultSummary) => {} +const DEFAULT_ON_COMPLETED = (summary: ResultSummary): void => {} /** * @private * @param {string[]} keys List of keys of the record in the result - * @return {void} + * @return {void} */ -const DEFAULT_ON_KEYS = (_keys: string[]) => {} +const DEFAULT_ON_KEYS = (keys: string[]): void => {} /** * The query result is the combination of the {@link ResultSummary} and @@ -88,16 +92,15 @@ interface ResultObserver { onError?: (error: Error) => void } - /** - * Defines a ResultObserver interface which can be used to enqueue records and dequeue + * Defines a ResultObserver interface which can be used to enqueue records and dequeue * them until the result is fully received. * @access private */ - interface QueuedResultObserver extends ResultObserver { - dequeue (): Promise> - head (): Promise> - get size (): number +interface QueuedResultObserver extends ResultObserver { + dequeue: () => Promise> + head: () => Promise> + size: number } /** @@ -108,16 +111,16 @@ interface ResultObserver { * @access public */ class Result implements Promise { - private _stack: string | null - private _streamObserverPromise: Promise + private readonly _stack: string | null + private readonly _streamObserverPromise: Promise private _p: Promise | null - private _query: Query - private _parameters: any - private _connectionHolder: connectionHolder.ConnectionHolder + private readonly _query: Query + private readonly _parameters: any + private readonly _connectionHolder: connectionHolder.ConnectionHolder private _keys: string[] | null private _summary: ResultSummary | null private _error: Error | null - private _watermarks: { high: number; low: number } + private readonly _watermarks: { high: number, low: number } /** * Inject the observer to be used. @@ -128,19 +131,19 @@ class Result implements Promise { * @param {Object} parameters - Map with parameters to use in query * @param {ConnectionHolder} connectionHolder - to be notified when result is either fully consumed or error happened. */ - constructor( + constructor ( streamObserverPromise: Promise, query: Query, parameters?: any, connectionHolder?: connectionHolder.ConnectionHolder, - watermarks: { high: number; low: number } = { high: Number.MAX_VALUE, low: Number.MAX_VALUE } + watermarks: { high: number, low: number } = { high: Number.MAX_VALUE, low: Number.MAX_VALUE } ) { this._stack = captureStacktrace() this._streamObserverPromise = streamObserverPromise this._p = null this._query = query - this._parameters = parameters || {} - this._connectionHolder = connectionHolder || EMPTY_CONNECTION_HOLDER + this._parameters = parameters ?? {} + this._connectionHolder = connectionHolder ?? EMPTY_CONNECTION_HOLDER this._keys = null this._summary = null this._error = null @@ -156,10 +159,10 @@ class Result implements Promise { * @returns {Promise} - Field keys, in the order they will appear in records. } */ - keys(): Promise { + keys (): Promise { if (this._keys !== null) { return Promise.resolve(this._keys) - } else if (this._error !== null) { + } else if (this._error !== null) { return Promise.reject(this._error) } return new Promise((resolve, reject) => { @@ -183,7 +186,7 @@ class Result implements Promise { * @returns {Promise} - Result summary. * */ - summary(): Promise { + summary (): Promise { if (this._summary !== null) { return Promise.resolve(this._summary) } else if (this._error !== null) { @@ -208,8 +211,8 @@ class Result implements Promise { * @private * @return {Promise} new Promise. */ - private _getOrCreatePromise(): Promise { - if (!this._p) { + private _getOrCreatePromise (): Promise { + if (this._p == null) { this._p = new Promise((resolve, reject) => { const records: Record[] = [] const observer = { @@ -238,56 +241,68 @@ class Result implements Promise { * @public * @returns {PeekableAsyncIterator} The async iterator for the Results */ - [Symbol.asyncIterator](): PeekableAsyncIterator { + [Symbol.asyncIterator] (): PeekableAsyncIterator { if (!this.isOpen()) { const error = newError('Result is already consumed') return { next: () => Promise.reject(error), - peek: () => Promise.reject(error), + peek: () => Promise.reject(error) } } const state: { - paused: boolean, - firstRun: boolean, - finished: boolean, - queuedObserver?: QueuedResultObserver, - streaming?: observer.ResultStreamObserver, - summary?: ResultSummary, + paused: boolean + firstRun: boolean + finished: boolean + queuedObserver?: QueuedResultObserver + streaming?: observer.ResultStreamObserver + summary?: ResultSummary } = { paused: true, firstRun: true, finished: false } - const controlFlow = () => { - if (!state.streaming) { - return; + const controlFlow = (): void => { + if (state.streaming == null) { + return } - const queueSizeIsOverHighOrEqualWatermark = state.queuedObserver!.size >= this._watermarks.high - const queueSizeIsBellowOrEqualLowWatermark = state.queuedObserver!.size <= this._watermarks.low + + const size = state.queuedObserver?.size ?? 0 + const queueSizeIsOverHighOrEqualWatermark = size >= this._watermarks.high + const queueSizeIsBellowOrEqualLowWatermark = size <= this._watermarks.low if (queueSizeIsOverHighOrEqualWatermark && !state.paused) { state.paused = true state.streaming.pause() - } else if (queueSizeIsBellowOrEqualLowWatermark && state.paused || state.firstRun && !queueSizeIsOverHighOrEqualWatermark ) { + } else if ((queueSizeIsBellowOrEqualLowWatermark && state.paused) || (state.firstRun && !queueSizeIsOverHighOrEqualWatermark)) { state.firstRun = false state.paused = false state.streaming.resume() } } - const initializeObserver = async () => { + const initializeObserver = async (): Promise => { if (state.queuedObserver === undefined) { state.queuedObserver = this._createQueuedResultObserver(controlFlow) state.streaming = await this._subscribe(state.queuedObserver, true).catch(() => undefined) controlFlow() } + return state.queuedObserver + } + + const assertSummary = (summary: ResultSummary | undefined): summary is ResultSummary => { + if (summary === undefined) { + throw newError('InvalidState: Result stream finished without Summary', PROTOCOL_ERROR) + } + return true } return { next: async () => { if (state.finished) { - return { done: true, value: state.summary! } + if (assertSummary(state.summary)) { + return { done: true, value: state.summary } + } } - await initializeObserver() - const next = await state.queuedObserver!.dequeue() - if (next.done) { + const queuedObserver = await initializeObserver() + const next = await queuedObserver.dequeue() + if (next.done === true) { state.finished = next.done state.summary = next.value } @@ -301,10 +316,12 @@ class Result implements Promise { }, peek: async () => { if (state.finished) { - return { done: true, value: state.summary! } + if (assertSummary(state.summary)) { + return { done: true, value: state.summary } + } } - await initializeObserver() - return await state.queuedObserver!.head() + const queuedObserver = await initializeObserver() + return await queuedObserver.head() } } } @@ -321,8 +338,8 @@ class Result implements Promise { */ then( onFulfilled?: - | ((value: QueryResult) => TResult1 | PromiseLike) - | null, + | ((value: QueryResult) => TResult1 | PromiseLike) + | null, onRejected?: ((reason: any) => TResult2 | PromiseLike) | null ): Promise { return this._getOrCreatePromise().then(onFulfilled, onRejected) @@ -336,7 +353,7 @@ class Result implements Promise { * @param {function(error: Neo4jError)} onRejected - Function to be called upon errors. * @return {Promise} promise. */ - catch( + catch ( onRejected?: ((reason: any) => TResult | PromiseLike) | null ): Promise { return this._getOrCreatePromise().catch(onRejected) @@ -350,7 +367,7 @@ class Result implements Promise { * @return {Promise} promise. */ [Symbol.toStringTag]: string - finally(onfinally?: (() => void) | null): Promise { + finally (onfinally?: (() => void) | null): Promise { return this._getOrCreatePromise().finally(onfinally) } @@ -365,7 +382,7 @@ class Result implements Promise { * @param {function(error: {message:string, code:string})} observer.onError - handle errors. * @return {void} */ - subscribe(observer: ResultObserver): void { + subscribe (observer: ResultObserver): void { this._subscribe(observer) .catch(() => {}) } @@ -387,7 +404,7 @@ class Result implements Promise { * @param {boolean} paused The flag to indicate if the stream should be started paused * @returns {Promise} The result stream observer. */ - _subscribe(observer: ResultObserver, paused: boolean = false): Promise { + _subscribe (observer: ResultObserver, paused: boolean = false): Promise { const _observer = this._decorateObserver(observer) return this._streamObserverPromise @@ -398,8 +415,10 @@ class Result implements Promise { o.subscribe(_observer) return o }) - .catch(error => { - _observer.onError!(error) + .catch(error => { + if (_observer.onError != null) { + _observer.onError(error) + } return Promise.reject(error) }) } @@ -411,35 +430,35 @@ class Result implements Promise { * @param {ResultObserver} observer The ResultObserver to decorate. * @returns The decorated result observer */ - _decorateObserver(observer: ResultObserver): ResultObserver { - const onCompletedOriginal = observer.onCompleted || DEFAULT_ON_COMPLETED - const onCompletedWrapper = (metadata: any) => { + _decorateObserver (observer: ResultObserver): ResultObserver { + const onCompletedOriginal = observer.onCompleted ?? DEFAULT_ON_COMPLETED + const onErrorOriginal = observer.onError ?? DEFAULT_ON_ERROR + const onKeysOriginal = observer.onKeys ?? DEFAULT_ON_KEYS + const onCompletedWrapper = (metadata: any): void => { this._createSummary(metadata).then(summary => { this._summary = summary return onCompletedOriginal.call(observer, summary) - }) + }).catch(onErrorOriginal) } - const onErrorOriginal = observer.onError || DEFAULT_ON_ERROR - const onErrorWrapper = (error: Error) => { + const onErrorWrapper = (error: Error): void => { // notify connection holder that the used connection is not needed any more because error happened // and result can't bee consumed any further; call the original onError callback after that this._connectionHolder.releaseConnection().then(() => { replaceStacktrace(error, this._stack) this._error = error onErrorOriginal.call(observer, error) - }) + }).catch(onErrorOriginal) } - const onKeysOriginal = observer.onKeys || DEFAULT_ON_KEYS - const onKeysWrapper = (keys: string[]) => { + const onKeysWrapper = (keys: string[]): void => { this._keys = keys return onKeysOriginal.call(observer, keys) } return { - onNext: observer.onNext? observer.onNext.bind(observer) : undefined, + onNext: (observer.onNext != null) ? observer.onNext.bind(observer) : undefined, onKeys: onKeysWrapper, onCompleted: onCompletedWrapper, onError: onErrorWrapper @@ -453,9 +472,10 @@ class Result implements Promise { * @since 4.0.0 * @returns {void} */ - _cancel(): void { + _cancel (): void { if (this._summary === null && this._error === null) { this._streamObserverPromise.then(o => o.cancel()) + .catch(() => {}) } } @@ -464,7 +484,7 @@ class Result implements Promise { * @param metadata * @returns */ - private _createSummary(metadata: any): Promise { + private _createSummary (metadata: any): Promise { const { validatedQuery: query, params: parameters @@ -481,7 +501,7 @@ class Result implements Promise { connectionHolder .releaseConnection() .then(() => - connection ? connection.protocol().version : undefined + connection?.protocol()?.version ), // onRejected: _ => undefined @@ -495,7 +515,7 @@ class Result implements Promise { /** * @access private */ - private _createQueuedResultObserver (onQueueSizeChanged: () => void): QueuedResultObserver { + private _createQueuedResultObserver (onQueueSizeChanged: () => void): QueuedResultObserver { interface ResolvablePromise { promise: Promise resolve: (arg: T) => any | undefined @@ -507,13 +527,13 @@ class Result implements Promise { resolvablePromise.promise = new Promise((resolve, reject) => { resolvablePromise.resolve = resolve resolvablePromise.reject = reject - }); - return resolvablePromise; + }) + return resolvablePromise } type QueuedResultElementOrError = IteratorResult | Error - function isError(elementOrError: QueuedResultElementOrError): elementOrError is Error { + function isError (elementOrError: QueuedResultElementOrError): elementOrError is Error { return elementOrError instanceof Error } @@ -532,7 +552,7 @@ class Result implements Promise { onError: (error: Error) => { observer._push(error) }, - _push(element: QueuedResultElementOrError) { + _push (element: QueuedResultElementOrError) { if (promiseHolder.resolvable !== null) { const resolvable = promiseHolder.resolvable promiseHolder.resolvable = null @@ -548,10 +568,10 @@ class Result implements Promise { }, dequeue: async () => { if (buffer.length > 0) { - const element = buffer.shift()! + const element = buffer.shift() ?? newError('Unexpected empty buffer', PROTOCOL_ERROR) onQueueSizeChanged() if (isError(element)) { - throw element + throw element } return element } @@ -562,13 +582,13 @@ class Result implements Promise { if (buffer.length > 0) { const element = buffer[0] if (isError(element)) { - throw element + throw element } return element } promiseHolder.resolvable = createResolvablePromise() try { - const element = await promiseHolder.resolvable.promise + const element = await promiseHolder.resolvable.promise buffer.unshift(element) return element } catch (error) { @@ -587,9 +607,9 @@ class Result implements Promise { } } -function captureStacktrace(): string | null { +function captureStacktrace (): string | null { const error = new Error('') - if (error.stack) { + if (error.stack != null) { return error.stack.replace(/^Error(\n\r)*/, '') // we don't need the 'Error\n' part, if only it exists } return null @@ -601,10 +621,11 @@ function captureStacktrace(): string | null { * @param {string| null} newStack The newStack * @returns {void} */ -function replaceStacktrace(error: Error, newStack?: string | null) { - if (newStack) { +function replaceStacktrace (error: Error, newStack?: string | null): void { + if (newStack != null) { // Error.prototype.toString() concatenates error.name and error.message nicely // then we add the rest of the stack trace + // eslint-disable-next-line @typescript-eslint/no-base-to-string error.stack = error.toString() + '\n' + newStack } } diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 4996d4f8c..e0e0bee59 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -16,14 +16,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { ResultStreamObserver, FailedObserver } from './internal/observers' + +/* eslint-disable @typescript-eslint/promise-function-async */ + +import { FailedObserver } from './internal/observers' import { validateQueryAndParameters } from './internal/util' -import { FETCH_ALL } from './internal/constants' +import { FETCH_ALL, ACCESS_MODE_READ, ACCESS_MODE_WRITE } from './internal/constants' import { newError } from './error' import Result from './result' import Transaction from './transaction' import { ConnectionHolder } from './internal/connection-holder' -import { ACCESS_MODE_READ, ACCESS_MODE_WRITE } from './internal/constants' import { TransactionExecutor } from './internal/transaction-executor' import { Bookmarks } from './internal/bookmarks' import { TxConfig } from './internal/tx-config' @@ -34,7 +36,7 @@ import { NumberOrInteger } from './graph-types' import TransactionPromise from './transaction-promise' import ManagedTransaction from './transaction-managed' -type ConnectionConsumer = (connection: Connection | void) => any | undefined +type ConnectionConsumer = (connection: Connection | null) => any | undefined type TransactionWork = (tx: Transaction) => Promise | T type ManagedTransactionWork = (tx: ManagedTransaction) => Promise | T @@ -51,22 +53,22 @@ interface TransactionConfig { * @access public */ class Session { - private _mode: SessionMode + private readonly _mode: SessionMode private _database: string - private _reactive: boolean - private _fetchSize: number - private _readConnectionHolder: ConnectionHolder - private _writeConnectionHolder: ConnectionHolder + private readonly _reactive: boolean + private readonly _fetchSize: number + private readonly _readConnectionHolder: ConnectionHolder + private readonly _writeConnectionHolder: ConnectionHolder private _open: boolean private _hasTx: boolean private _lastBookmarks: Bookmarks - private _transactionExecutor: TransactionExecutor - private _impersonatedUser?: string - private _onComplete: (meta: any) => void + private readonly _transactionExecutor: TransactionExecutor + private readonly _impersonatedUser?: string + private readonly _onComplete: (meta: any) => void private _databaseNameResolved: boolean - private _lowRecordWatermark: number - private _highRecordWatermark: number - private _results: Result[] + private readonly _lowRecordWatermark: number + private readonly _highRecordWatermark: number + private readonly _results: Result[] /** * @constructor * @protected @@ -80,7 +82,7 @@ class Session { * @param {number} args.fetchSize - Defines how many records is pulled in each pulling batch * @param {string} args.impersonatedUser - The username which the user wants to impersonate for the duration of the session. */ - constructor({ + constructor ({ mode, connectionProvider, bookmarks, @@ -96,7 +98,7 @@ class Session { database: string config: any reactive: boolean - fetchSize: number, + fetchSize: number impersonatedUser?: string }) { this._mode = mode @@ -123,7 +125,7 @@ class Session { this._open = true this._hasTx = false this._impersonatedUser = impersonatedUser - this._lastBookmarks = bookmarks || Bookmarks.empty() + this._lastBookmarks = bookmarks ?? Bookmarks.empty() this._transactionExecutor = _createTransactionExecutor(config) this._onComplete = this._onCompleteCallback.bind(this) this._databaseNameResolved = this._database !== '' @@ -144,7 +146,7 @@ class Session { * @param {TransactionConfig} [transactionConfig] - Configuration for the new auto-commit transaction. * @return {Result} New Result. */ - run( + run ( query: Query, parameters?: any, transactionConfig?: TransactionConfig @@ -153,7 +155,7 @@ class Session { query, parameters ) - const autoCommitTxConfig = transactionConfig + const autoCommitTxConfig = (transactionConfig != null) ? new TxConfig(transactionConfig) : TxConfig.empty() @@ -176,7 +178,7 @@ class Session { return result } - _run( + _run ( query: Query, parameters: any, customRunner: ConnectionConsumer @@ -210,7 +212,7 @@ class Session { return new Result(observerPromise, query, parameters, connectionHolder, watermarks) } - async _acquireConnection(connectionConsumer: ConnectionConsumer) { + _acquireConnection (connectionConsumer: ConnectionConsumer): Promise { let promise const connectionHolder = this._connectionHolderWithMode(this._mode) if (!this._open) { @@ -247,21 +249,21 @@ class Session { * @param {TransactionConfig} [transactionConfig] - Configuration for the new auto-commit transaction. * @returns {TransactionPromise} New Transaction. */ - beginTransaction(transactionConfig?: TransactionConfig): TransactionPromise { + beginTransaction (transactionConfig?: TransactionConfig): TransactionPromise { // this function needs to support bookmarks parameter for backwards compatibility // parameter was of type {string|string[]} and represented either a single or multiple bookmarks // that's why we need to check parameter type and decide how to interpret the value const arg = transactionConfig let txConfig = TxConfig.empty() - if (arg) { + if (arg != null) { txConfig = new TxConfig(arg) } return this._beginTransaction(this._mode, txConfig) } - _beginTransaction(accessMode: SessionMode, txConfig: TxConfig): TransactionPromise { + _beginTransaction (accessMode: SessionMode, txConfig: TxConfig): TransactionPromise { if (!this._open) { throw newError('Cannot begin a transaction on a closed session.') } @@ -296,7 +298,7 @@ class Session { * @private * @returns {void} */ - _assertSessionIsOpen() { + _assertSessionIsOpen (): void { if (!this._open) { throw newError('You cannot run more transactions on a closed session.') } @@ -306,7 +308,7 @@ class Session { * @private * @returns {void} */ - _transactionClosed() { + _transactionClosed (): void { this._hasTx = false } @@ -314,10 +316,10 @@ class Session { * Return the bookmarks received following the last completed {@link Transaction}. * * @deprecated This method will be removed in version 6.0. Please, use {@link Session#lastBookmarks} instead. - * + * * @return {string[]} A reference to a previous transaction. */ - lastBookmark(): string[] { + lastBookmark (): string[] { return this.lastBookmarks() } @@ -326,7 +328,7 @@ class Session { * * @return {string[]} A reference to a previous transaction. */ - lastBookmarks(): string[] { + lastBookmarks (): string[] { return this._lastBookmarks.values() } @@ -403,7 +405,7 @@ class Session { * @return {Promise} Resolved promise as returned by the given function or rejected promise when given * function or commit fails. */ - executeRead( + executeRead( transactionWork: ManagedTransactionWork, transactionConfig?: TransactionConfig ): Promise { @@ -458,9 +460,9 @@ class Session { * @param {string|undefined} database The resolved database name * @returns {void} */ - _onDatabaseNameResolved(database?: string): void { + _onDatabaseNameResolved (database?: string): void { if (!this._databaseNameResolved) { - const normalizedDatabase = database || '' + const normalizedDatabase = database ?? '' this._database = normalizedDatabase this._readConnectionHolder.setDatabase(normalizedDatabase) this._writeConnectionHolder.setDatabase(normalizedDatabase) @@ -474,8 +476,8 @@ class Session { * @param {Bookmarks} newBookmarks - The new bookmarks. * @returns {void} */ - _updateBookmarks(newBookmarks?: Bookmarks): void { - if (newBookmarks && !newBookmarks.isEmpty()) { + _updateBookmarks (newBookmarks?: Bookmarks): void { + if ((newBookmarks != null) && !newBookmarks.isEmpty()) { this._lastBookmarks = newBookmarks } } @@ -484,7 +486,7 @@ class Session { * Close this session. * @return {Promise} */ - async close(): Promise { + async close (): Promise { if (this._open) { this._open = false @@ -497,13 +499,13 @@ class Session { } } - _connectionHolderWithMode(mode: SessionMode): ConnectionHolder { + _connectionHolderWithMode (mode: SessionMode): ConnectionHolder { if (mode === ACCESS_MODE_READ) { return this._readConnectionHolder } else if (mode === ACCESS_MODE_WRITE) { return this._writeConnectionHolder } else { - throw newError('Unknown access mode: ' + mode) + throw newError('Unknown access mode: ' + (mode as string)) } } @@ -512,7 +514,7 @@ class Session { * @param {Object} meta Connection metadatada * @returns {void} */ - _onCompleteCallback(meta: { bookmark: string | string[] }): void { + _onCompleteCallback (meta: { bookmark: string | string[] }): void { this._updateBookmarks(new Bookmarks(meta.bookmark)) } @@ -520,7 +522,7 @@ class Session { * @private * @returns {void} */ - private _calculateWatermaks(): { low: number; high: number } { + private _calculateWatermaks (): { low: number, high: number } { if (this._fetchSize === FETCH_ALL) { return { low: Number.MAX_VALUE, // we shall always lower than this number to enable auto pull @@ -536,12 +538,12 @@ class Session { /** * @protected */ - static _validateSessionMode(rawMode?: SessionMode): SessionMode { - const mode = rawMode || ACCESS_MODE_WRITE + static _validateSessionMode (rawMode?: SessionMode): SessionMode { + const mode: string = rawMode ?? ACCESS_MODE_WRITE if (mode !== ACCESS_MODE_READ && mode !== ACCESS_MODE_WRITE) { throw newError('Illegal session mode ' + mode) } - return mode + return mode as SessionMode } } @@ -550,13 +552,10 @@ class Session { * @param {object} config * @returns {TransactionExecutor} The transaction executor */ -function _createTransactionExecutor(config?: { +function _createTransactionExecutor (config?: { maxTransactionRetryTime: number | null }): TransactionExecutor { - const maxRetryTimeMs = - config && config.maxTransactionRetryTime - ? config.maxTransactionRetryTime - : null + const maxRetryTimeMs = config?.maxTransactionRetryTime ?? null return new TransactionExecutor(maxRetryTimeMs) } diff --git a/packages/core/src/spatial-types.ts b/packages/core/src/spatial-types.ts index b8e67750b..83d150a6f 100644 --- a/packages/core/src/spatial-types.ts +++ b/packages/core/src/spatial-types.ts @@ -39,12 +39,12 @@ export class Point { * @param {number} y - The `y` coordinate of the point. * @param {number} [z=undefined] - The `z` coordinate of the point or `undefined` if point has 2 dimensions. */ - constructor(srid: T, x: number, y: number, z?: number) { + constructor (srid: T, x: number, y: number, z?: number) { /** * The coordinate reference system identifier. * @type {T} */ - this.srid = assertNumberOrInteger(srid, 'SRID') + this.srid = assertNumberOrInteger(srid, 'SRID') as T /** * The `x` coordinate of the point. * @type {number} @@ -66,8 +66,8 @@ export class Point { /** * @ignore */ - toString(): string { - return this.z || this.z === 0 + toString (): string { + return this.z != null && !isNaN(this.z) ? `Point{srid=${formatAsFloat(this.srid)}, x=${formatAsFloat( this.x )}, y=${formatAsFloat(this.y)}, z=${formatAsFloat(this.z)}}` @@ -77,8 +77,8 @@ export class Point { } } -function formatAsFloat(number: NumberOrInteger) { - return Number.isInteger(number) ? number + '.0' : number.toString() +function formatAsFloat (number: NumberOrInteger): string { + return Number.isInteger(number) ? number.toString() + '.0' : number.toString() } Object.defineProperty(Point.prototype, POINT_IDENTIFIER_PROPERTY, { @@ -93,6 +93,6 @@ Object.defineProperty(Point.prototype, POINT_IDENTIFIER_PROPERTY, { * @param {Object} obj the object to test. * @return {boolean} `true` if given object is a {@link Point}, `false` otherwise. */ -export function isPoint(obj?: any): obj is Point { - return (obj && obj[POINT_IDENTIFIER_PROPERTY]) === true +export function isPoint (obj?: any): obj is Point { + return obj != null && obj[POINT_IDENTIFIER_PROPERTY] === true } diff --git a/packages/core/src/temporal-types.ts b/packages/core/src/temporal-types.ts index 7421aa90d..60a5f6ddd 100644 --- a/packages/core/src/temporal-types.ts +++ b/packages/core/src/temporal-types.ts @@ -58,7 +58,7 @@ export class Duration { * @param {NumberOrInteger} seconds - The number of seconds for the new duration. * @param {NumberOrInteger} nanoseconds - The number of nanoseconds for the new duration. */ - constructor(months: T, days: T, seconds: T, nanoseconds: T) { + constructor (months: T, days: T, seconds: T, nanoseconds: T) { /** * The number of months. * @type {NumberOrInteger} @@ -87,7 +87,7 @@ export class Duration { /** * @ignore */ - toString() { + toString (): string { return util.durationToIsoString( this.months, this.days, @@ -108,7 +108,7 @@ Object.defineProperty( * @param {Object} obj the object to test. * @return {boolean} `true` if given object is a {@link Duration}, `false` otherwise. */ -export function isDuration(obj: object): obj is Duration { +export function isDuration (obj: object): obj is Duration { return hasIdentifierProperty(obj, DURATION_IDENTIFIER_PROPERTY) } @@ -128,7 +128,7 @@ export class LocalTime { * @param {NumberOrInteger} second - The second for the new local time. * @param {NumberOrInteger} nanosecond - The nanosecond for the new local time. */ - constructor(hour: T, minute: T, second: T, nanosecond: T) { + constructor (hour: T, minute: T, second: T, nanosecond: T) { /** * The hour. * @type {NumberOrInteger} @@ -159,7 +159,7 @@ export class LocalTime { * @param {NumberOrInteger|undefined} nanosecond - The optional amount of nanoseconds. * @return {LocalTime} New LocalTime. */ - static fromStandardDate( + static fromStandardDate ( standardDate: StandardDate, nanosecond?: NumberOrInteger ): LocalTime { @@ -177,15 +177,15 @@ export class LocalTime { totalNanoseconds instanceof Integer ? totalNanoseconds.toInt() : typeof totalNanoseconds === 'bigint' - ? int(totalNanoseconds).toInt() - : totalNanoseconds + ? int(totalNanoseconds).toInt() + : totalNanoseconds ) } /** * @ignore */ - toString(): string { + toString (): string { return util.timeToIsoString( this.hour, this.minute, @@ -206,7 +206,7 @@ Object.defineProperty( * @param {Object} obj the object to test. * @return {boolean} `true` if given object is a {@link LocalTime}, `false` otherwise. */ -export function isLocalTime(obj: object): boolean { +export function isLocalTime (obj: object): boolean { return hasIdentifierProperty(obj, LOCAL_TIME_IDENTIFIER_PROPERTY) } @@ -229,7 +229,7 @@ export class Time { * @param {NumberOrInteger} timeZoneOffsetSeconds - The time zone offset in seconds. Value represents the difference, in seconds, from UTC to local time. * This is different from standard JavaScript `Date.getTimezoneOffset()` which is the difference, in minutes, from local time to UTC. */ - constructor( + constructor ( hour: T, minute: T, second: T, @@ -274,7 +274,7 @@ export class Time { * @param {NumberOrInteger|undefined} nanosecond - The optional amount of nanoseconds. * @return {Time} New Time. */ - static fromStandardDate( + static fromStandardDate ( standardDate: StandardDate, nanosecond?: NumberOrInteger ): Time { @@ -292,7 +292,7 @@ export class Time { /** * @ignore */ - toString() { + toString (): string { return ( util.timeToIsoString( this.hour, @@ -315,7 +315,7 @@ Object.defineProperty( * @param {Object} obj the object to test. * @return {boolean} `true` if given object is a {@link Time}, `false` otherwise. */ -export function isTime(obj: object): obj is Time { +export function isTime (obj: object): obj is Time { return hasIdentifierProperty(obj, TIME_IDENTIFIER_PROPERTY) } @@ -333,7 +333,7 @@ export class Date { * @param {NumberOrInteger} month - The month for the new local date. * @param {NumberOrInteger} day - The day for the new local date. */ - constructor(year: T, month: T, day: T) { + constructor (year: T, month: T, day: T) { /** * The year. * @type {NumberOrInteger} @@ -358,7 +358,7 @@ export class Date { * @param {global.Date} standardDate - The standard JavaScript date to convert. * @return {Date} New Date. */ - static fromStandardDate(standardDate: StandardDate): Date { + static fromStandardDate (standardDate: StandardDate): Date { verifyStandardDateAndNanos(standardDate) return new Date( @@ -376,14 +376,14 @@ export class Date { * * @returns {StandardDate} Standard JavaScript `Date` at `00:00:00.000` UTC. */ - toStandardDate(): StandardDate { + toStandardDate (): StandardDate { return util.isoStringToStandardDate(this.toString()) } /** * @ignore */ - toString() { + toString (): string { return util.dateToIsoString(this.year, this.month, this.day) } } @@ -399,7 +399,7 @@ Object.defineProperty( * @param {Object} obj - The object to test. * @return {boolean} `true` if given object is a {@link Date}, `false` otherwise. */ -export function isDate(obj: object): boolean { +export function isDate (obj: object): boolean { return hasIdentifierProperty(obj, DATE_IDENTIFIER_PROPERTY) } @@ -425,7 +425,7 @@ export class LocalDateTime { * @param {NumberOrInteger} second - The second for the new local time. * @param {NumberOrInteger} nanosecond - The nanosecond for the new local time. */ - constructor( + constructor ( year: T, month: T, day: T, @@ -479,7 +479,7 @@ export class LocalDateTime { * @param {NumberOrInteger|undefined} nanosecond - The optional amount of nanoseconds. * @return {LocalDateTime} New LocalDateTime. */ - static fromStandardDate( + static fromStandardDate ( standardDate: StandardDate, nanosecond?: NumberOrInteger ): LocalDateTime { @@ -501,14 +501,14 @@ export class LocalDateTime { * * @returns {StandardDate} Standard JavaScript `Date` at the local timezone */ - toStandardDate(): StandardDate { + toStandardDate (): StandardDate { return util.isoStringToStandardDate(this.toString()) } /** * @ignore */ - toString(): string { + toString (): string { return localDateTimeToString( this.year, this.month, @@ -532,7 +532,7 @@ Object.defineProperty( * @param {Object} obj - The object to test. * @return {boolean} `true` if given object is a {@link LocalDateTime}, `false` otherwise. */ -export function isLocalDateTime(obj: any): obj is LocalDateTime { +export function isLocalDateTime (obj: any): obj is LocalDateTime { return hasIdentifierProperty(obj, LOCAL_DATE_TIME_IDENTIFIER_PROPERTY) } @@ -564,7 +564,7 @@ export class DateTime { * This is different from standard JavaScript `Date.getTimezoneOffset()` which is the difference, in minutes, from local time to UTC. * @param {string|null} timeZoneId - The time zone id for the new date-time. Either this argument or `timeZoneOffsetSeconds` should be defined. */ - constructor( + constructor ( year: T, month: T, day: T, @@ -630,7 +630,7 @@ export class DateTime { * * @type {string} */ - this.timeZoneId = id || undefined + this.timeZoneId = id ?? undefined Object.freeze(this) } @@ -641,7 +641,7 @@ export class DateTime { * @param {NumberOrInteger|undefined} nanosecond - The optional amount of nanoseconds. * @return {DateTime} New DateTime. */ - static fromStandardDate( + static fromStandardDate ( standardDate: StandardDate, nanosecond?: NumberOrInteger ): DateTime { @@ -666,7 +666,7 @@ export class DateTime { * @returns {StandardDate} Standard JavaScript `Date` at the defined time zone offset * @throws {Error} If the time zone offset is not defined in the object. */ - toStandardDate(): StandardDate { + toStandardDate (): StandardDate { if (this.timeZoneOffsetSeconds === undefined) { throw new Error('Requires DateTime created with time zone offset') } @@ -676,7 +676,7 @@ export class DateTime { /** * @ignore */ - toString(): string { + toString (): string { const localDateTimeStr = localDateTimeToString( this.year, this.month, @@ -686,9 +686,9 @@ export class DateTime { this.second, this.nanosecond ) - const timeZoneStr = this.timeZoneId + const timeZoneStr = this.timeZoneId != null ? `[${this.timeZoneId}]` - : util.timeZoneOffsetToIsoString(this.timeZoneOffsetSeconds || 0) + : util.timeZoneOffsetToIsoString(this.timeZoneOffsetSeconds ?? 0) return localDateTimeStr + timeZoneStr } } @@ -704,15 +704,15 @@ Object.defineProperty( * @param {Object} obj - The object to test. * @return {boolean} `true` if given object is a {@link DateTime}, `false` otherwise. */ -export function isDateTime(obj: object): boolean { +export function isDateTime (obj: object): boolean { return hasIdentifierProperty(obj, DATE_TIME_IDENTIFIER_PROPERTY) } -function hasIdentifierProperty(obj: any, property: string) { - return (obj && obj[property]) === true +function hasIdentifierProperty (obj: any, property: string): boolean { + return obj != null && obj[property] === true } -function localDateTimeToString( +function localDateTimeToString ( year: NumberOrInteger, month: NumberOrInteger, day: NumberOrInteger, @@ -734,12 +734,12 @@ function localDateTimeToString( * @param {string | null } timeZoneId * @returns {Array} */ -function verifyTimeZoneArguments( +function verifyTimeZoneArguments ( timeZoneOffsetSeconds?: NumberOrInteger, timeZoneId?: string | null ): [NumberOrInteger | undefined | null, string | undefined | null] { - const offsetDefined = timeZoneOffsetSeconds || timeZoneOffsetSeconds === 0 - const idDefined = timeZoneId && timeZoneId !== '' + const offsetDefined = timeZoneOffsetSeconds !== null && timeZoneOffsetSeconds !== undefined + const idDefined = timeZoneId !== null && timeZoneId !== undefined && timeZoneId !== '' if (offsetDefined && !idDefined) { assertNumberOrInteger(timeZoneOffsetSeconds, 'Time zone offset in seconds') @@ -749,10 +749,12 @@ function verifyTimeZoneArguments( return [undefined, timeZoneId] } else if (offsetDefined && idDefined) { throw newError( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `Unable to create DateTime with both time zone offset and id. Please specify either of them. Given offset: ${timeZoneOffsetSeconds} and id: ${timeZoneId}` ) } else { throw newError( + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `Unable to create DateTime without either time zone offset or id. Please specify either of them. Given offset: ${timeZoneOffsetSeconds} and id: ${timeZoneId}` ) } @@ -764,7 +766,7 @@ function verifyTimeZoneArguments( * @param {NumberOrInteger} nanosecond * @returns {void} */ -function verifyStandardDateAndNanos( +function verifyStandardDateAndNanos ( standardDate: StandardDate, nanosecond?: NumberOrInteger ): void { diff --git a/packages/core/src/transaction-managed.ts b/packages/core/src/transaction-managed.ts index e9a44b440..0bd566f82 100644 --- a/packages/core/src/transaction-managed.ts +++ b/packages/core/src/transaction-managed.ts @@ -21,22 +21,20 @@ import Result from './result' import Transaction from './transaction' import { Query } from './types' -interface Run { - (query: Query, parameters?: any): Result -} +type Run = (query: Query, parameters?: any) => Result /** * Represents a transaction that is managed by the transaction executor. - * + * * @public */ class ManagedTransaction { - private _run: Run + private readonly _run: Run /** * @private */ - private constructor({ run }: { run: Run }) { + private constructor ({ run }: { run: Run }) { /** * @private */ @@ -48,7 +46,7 @@ class ManagedTransaction { * @param {Transaction} tx - Transaction to wrap * @returns {ManagedTransaction} the ManagedTransaction */ - static fromTransaction(tx: Transaction): ManagedTransaction { + static fromTransaction (tx: Transaction): ManagedTransaction { return new ManagedTransaction({ run: tx.run.bind(tx) }) @@ -62,7 +60,7 @@ class ManagedTransaction { * @param {Object} parameters - Map with parameters to use in query * @return {Result} New Result */ - run(query: Query, parameters?: any): Result { + run (query: Query, parameters?: any): Result { return this._run(query, parameters) } } diff --git a/packages/core/src/transaction-promise.ts b/packages/core/src/transaction-promise.ts index 5a695d2ea..344755e82 100644 --- a/packages/core/src/transaction-promise.ts +++ b/packages/core/src/transaction-promise.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/promise-function-async */ + import Transaction from './transaction' import { ConnectionHolder @@ -30,18 +32,18 @@ import { TxConfig } from './internal/tx-config' * * Resolving this object promise verifies the result of the transaction begin and returns the {@link Transaction} object in case of success. * - * The object can still also used as {@link Transaction} for convenience. The result of begin will be checked + * The object can still also used as {@link Transaction} for convenience. The result of begin will be checked * during the next API calls in the object as it is in the transaction. * * @access public */ -class TransactionPromise extends Transaction implements Promise{ - [Symbol.toStringTag]: string = "TransactionPromise" - private _beginError?: Error; - private _beginMetadata?: any; - private _beginPromise?: Promise; - private _reject?: (error: Error) => void; - private _resolve?: (value: Transaction | PromiseLike) => void; +class TransactionPromise extends Transaction implements Promise { + [Symbol.toStringTag]: string = 'TransactionPromise' + private _beginError?: Error + private _beginMetadata?: any + private _beginPromise?: Promise + private _reject?: (error: Error) => void + private _resolve?: (value: Transaction | PromiseLike) => void /** * @constructor @@ -54,7 +56,7 @@ class TransactionPromise extends Transaction implements Promise{ * @param {number} fetchSize - the record fetch size in each pulling batch. * @param {string} impersonatedUser - The name of the user which should be impersonated for the duration of the session. */ - constructor({ + constructor ({ connectionHolder, onClose, onBookmarks, @@ -71,8 +73,8 @@ class TransactionPromise extends Transaction implements Promise{ onConnection: () => void reactive: boolean fetchSize: number - impersonatedUser?: string, - highRecordWatermark: number, + impersonatedUser?: string + highRecordWatermark: number lowRecordWatermark: number }) { super({ @@ -97,13 +99,13 @@ class TransactionPromise extends Transaction implements Promise{ */ then( onfulfilled?: - ((value: Transaction) => TResult1 | PromiseLike) - | null, + ((value: Transaction) => TResult1 | PromiseLike) + | null, onrejected?: - ((reason: any) => TResult2 | PromiseLike) - | null + ((reason: any) => TResult2 | PromiseLike) + | null ): Promise { - return this._getOrCreateBeginPromise().then(onfulfilled, onrejected); + return this._getOrCreateBeginPromise().then(onfulfilled, onrejected) } /** @@ -112,8 +114,8 @@ class TransactionPromise extends Transaction implements Promise{ * @param {function(error: Neo4jError)} onRejected - Function to be called upon errors. * @return {Promise} promise. */ - catch(onrejected?: ((reason: any) => TResult | PromiseLike) | null): Promise { - return this._getOrCreateBeginPromise().catch(onrejected); + catch (onrejected?: ((reason: any) => TResult | PromiseLike) | null): Promise { + return this._getOrCreateBeginPromise().catch(onrejected) } /** @@ -122,31 +124,30 @@ class TransactionPromise extends Transaction implements Promise{ * @param {function()|null} onfinally - function when the promise finished * @return {Promise} promise. */ - finally(onfinally?: (() => void) | null): Promise { - return this._getOrCreateBeginPromise().finally(onfinally); + finally (onfinally?: (() => void) | null): Promise { + return this._getOrCreateBeginPromise().finally(onfinally) } - private _getOrCreateBeginPromise(): Promise { - if (!this._beginPromise) { + private _getOrCreateBeginPromise (): Promise { + if (this._beginPromise == null) { this._beginPromise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - if (this._beginError) { - reject(this._beginError); + this._resolve = resolve + this._reject = reject + if (this._beginError != null) { + reject(this._beginError) } - if (this._beginMetadata) { - resolve(this._toTransaction()); + if (this._beginMetadata != null) { + resolve(this._toTransaction()) } - }); + }) } - return this._beginPromise; + return this._beginPromise } /** * @access private */ - private _toTransaction(): Transaction { - //@ts-ignore + private _toTransaction (): Transaction { return { ...this, run: super.run.bind(this), @@ -154,28 +155,28 @@ class TransactionPromise extends Transaction implements Promise{ rollback: super.rollback.bind(this), close: super.close.bind(this), isOpen: super.isOpen.bind(this), - _begin: this._begin.bind(this), + _begin: this._begin.bind(this) } } /** * @access private */ - _begin(bookmarks: string | Bookmarks | string[], txConfig: TxConfig): void { + _begin (bookmarks: string | Bookmarks | string[], txConfig: TxConfig): void { return super._begin(bookmarks, txConfig, { onError: this._onBeginError.bind(this), onComplete: this._onBeginMetadata.bind(this) - }); + }) } /** * @access private * @returns {void} */ - private _onBeginError(error: Error): void { - this._beginError = error; - if (this._reject) { - this._reject(error); + private _onBeginError (error: Error): void { + this._beginError = error + if (this._reject != null) { + this._reject(error) } } @@ -183,13 +184,12 @@ class TransactionPromise extends Transaction implements Promise{ * @access private * @returns {void} */ - private _onBeginMetadata(metadata: any): void { - this._beginMetadata = metadata || {}; - if (this._resolve) { - this._resolve(this._toTransaction()); + private _onBeginMetadata (metadata: any): void { + this._beginMetadata = metadata ?? {} + if (this._resolve != null) { + this._resolve(this._toTransaction()) } } - } export default TransactionPromise diff --git a/packages/core/src/transaction.ts b/packages/core/src/transaction.ts index d992d0a33..d22876bf5 100644 --- a/packages/core/src/transaction.ts +++ b/packages/core/src/transaction.ts @@ -16,6 +16,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +/* eslint-disable @typescript-eslint/promise-function-async */ import { validateQueryAndParameters } from './internal/util' import Connection from './connection' import { @@ -42,19 +44,19 @@ import { Query } from './types' * @access public */ class Transaction { - private _connectionHolder: ConnectionHolder - private _reactive: boolean + private readonly _connectionHolder: ConnectionHolder + private readonly _reactive: boolean private _state: any - private _onClose: () => void - private _onBookmarks: (bookmarks: Bookmarks) => void - private _onConnection: () => void - private _onError: (error: Error) => Promise - private _onComplete: (metadata: any) => void - private _fetchSize: number - private _results: any[] - private _impersonatedUser?: string - private _lowRecordWatermak: number - private _highRecordWatermark: number + private readonly _onClose: () => void + private readonly _onBookmarks: (bookmarks: Bookmarks) => void + private readonly _onConnection: () => void + private readonly _onError: (error: Error) => Promise + private readonly _onComplete: (metadata: any) => void + private readonly _fetchSize: number + private readonly _results: any[] + private readonly _impersonatedUser?: string + private readonly _lowRecordWatermak: number + private readonly _highRecordWatermark: number /** * @constructor @@ -69,7 +71,7 @@ class Transaction { * @param {number} highRecordWatermark - The high watermark for the record buffer. * @param {number} lowRecordWatermark - The low watermark for the record buffer. */ - constructor({ + constructor ({ connectionHolder, onClose, onBookmarks, @@ -86,8 +88,8 @@ class Transaction { onConnection: () => void reactive: boolean fetchSize: number - impersonatedUser?: string, - highRecordWatermark: number, + impersonatedUser?: string + highRecordWatermark: number lowRecordWatermark: number }) { this._connectionHolder = connectionHolder @@ -111,7 +113,7 @@ class Transaction { * @param {TxConfig} txConfig * @returns {void} */ - _begin(bookmarks: Bookmarks | string | string[], txConfig: TxConfig, events?: { + _begin (bookmarks: Bookmarks | string | string[], txConfig: TxConfig, events?: { onError: (error: Error) => void onComplete: (metadata: any) => void }): void { @@ -119,7 +121,7 @@ class Transaction { .getConnection() .then(connection => { this._onConnection() - if (connection) { + if (connection != null) { return connection.protocol().beginTransaction({ bookmarks: bookmarks, txConfig: txConfig, @@ -127,13 +129,13 @@ class Transaction { database: this._connectionHolder.database(), impersonatedUser: this._impersonatedUser, beforeError: (error: Error) => { - if (events) { + if (events != null) { events.onError(error) } - return this._onError(error).catch(() => {}) + return this._onError(error) }, afterComplete: (metadata: any) => { - if (events) { + if (events != null) { events.onComplete(metadata) } return this._onComplete(metadata) @@ -143,8 +145,8 @@ class Transaction { throw newError('No connection available') } }) - .catch(error => { - if (events) { + .catch(error => { + if (events != null) { events.onError(error) } this._onError(error).catch(() => {}) @@ -159,13 +161,13 @@ class Transaction { * @param {Object} parameters - Map with parameters to use in query * @return {Result} New Result */ - run(query: Query, parameters?: any): Result { + run (query: Query, parameters?: any): Result { const { validatedQuery, params } = validateQueryAndParameters( query, parameters ) - var result = this._state.run(validatedQuery, params, { + const result = this._state.run(validatedQuery, params, { connectionHolder: this._connectionHolder, onError: this._onError, onComplete: this._onComplete, @@ -186,7 +188,7 @@ class Transaction { * * @returns {Promise} An empty promise if committed successfully or error if any error happened during commit. */ - commit(): Promise { + commit (): Promise { const committed = this._state.commit({ connectionHolder: this._connectionHolder, onError: this._onError, @@ -213,7 +215,7 @@ class Transaction { * @returns {Promise} An empty promise if rolled back successfully or error if any error happened during * rollback. */ - rollback(): Promise { + rollback (): Promise { const rolledback = this._state.rollback({ connectionHolder: this._connectionHolder, onError: this._onError, @@ -236,7 +238,7 @@ class Transaction { * Check if this transaction is active, which means commit and rollback did not happen. * @return {boolean} `true` when not committed and not rolled back, `false` otherwise. */ - isOpen(): boolean { + isOpen (): boolean { return this._state === _states.ACTIVE } @@ -247,13 +249,13 @@ class Transaction { * * @returns {Promise} An empty promise if closed successfully or error if any error happened during */ - async close(): Promise { + async close (): Promise { if (this.isOpen()) { await this.rollback() } } - _onErrorCallback(err: any): Promise { + _onErrorCallback (): Promise { // error will be "acknowledged" by sending a RESET message // database will then forget about this transaction and cleanup all corresponding resources // it is thus safe to move this transaction to a FAILED state and disallow any further interactions with it @@ -269,7 +271,7 @@ class Transaction { * @param {object} meta The meta with bookmarks * @returns {void} */ - _onCompleteCallback(meta: { bookmark?: string | string[] }): void { + _onCompleteCallback (meta: { bookmark?: string | string[] }): void { this._onBookmarks(new Bookmarks(meta.bookmark)) } } @@ -351,7 +353,7 @@ const _states = { .getConnection() .then(conn => { onConnection() - if (conn) { + if (conn != null) { return conn.protocol().run(query, parameters, { bookmarks: Bookmarks.empty(), txConfig: TxConfig.empty(), @@ -436,8 +438,8 @@ const _states = { query, parameters, connectionHolder, - 0, // high watermark - 0 // low watermark + 0, // high watermark + 0 // low watermark ) } }, @@ -587,7 +589,7 @@ const _states = { * @param {function() : any} onConnection * @param {list>}pendingResults all run results in this transaction */ -function finishTransaction( +function finishTransaction ( commit: boolean, connectionHolder: ConnectionHolder, onError: (err: Error) => any, @@ -601,7 +603,7 @@ function finishTransaction( onConnection() pendingResults.forEach(r => r._cancel()) return Promise.all(pendingResults.map(result => result.summary())).then(results => { - if (connection) { + if (connection != null) { if (commit) { return connection.protocol().commitTransaction({ beforeError: onError, @@ -630,7 +632,7 @@ function finishTransaction( { high: Number.MAX_VALUE, low: Number.MAX_VALUE - }, + } ) } @@ -645,7 +647,7 @@ function finishTransaction( * @return {Result} new result. * @private */ -function newCompletedResult( +function newCompletedResult ( observerPromise: ResultStreamObserver | Promise, query: Query, parameters: any, @@ -657,7 +659,7 @@ function newCompletedResult( Promise.resolve(observerPromise), query, parameters, - new ReadOnlyConnectionHolder(connectionHolder || EMPTY_CONNECTION_HOLDER), + new ReadOnlyConnectionHolder(connectionHolder ?? EMPTY_CONNECTION_HOLDER), { low: lowRecordWatermark, high: highRecordWatermark diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 54889ade7..63140cc16 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -20,7 +20,7 @@ /** * @private */ -export type Query = string | String | { text: string; parameters?: any } +export type Query = string | String | { text: string, parameters?: any } export type EncryptionLevel = 'ENCRYPTION_ON' | 'ENCRYPTION_OFF' @@ -40,7 +40,7 @@ export type TrustStrategy = | 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' | 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES' -export type Parameters = { [key: string]: any } +export interface Parameters { [key: string]: any } export interface AuthToken { scheme: string principal: string @@ -75,7 +75,7 @@ export interface PeekableAsyncIterator exte /** * Returns the next element in the iteration without advancing the iterator. * - * @return {IteratorResult} The next element in the iteration. */ - peek(): Promise> + peek: () => Promise> } From 2023ef2d713b0bc210f66996bff00bf756f9fdad Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Tue, 19 Apr 2022 19:39:35 +0200 Subject: [PATCH 03/13] Applying linter to packages/core/test --- packages/core/test/auth.test.ts | 1 - packages/core/test/driver.test.ts | 59 ++-- packages/core/test/error.test.ts | 56 ++- packages/core/test/graph-types.test.ts | 123 ++++--- packages/core/test/integer.test.ts | 339 ++++++++++--------- packages/core/test/internal/url-util.test.ts | 24 +- packages/core/test/record.test.ts | 2 +- packages/core/test/result.test.ts | 158 +++++---- packages/core/test/session.test.ts | 77 ++--- packages/core/test/temporal-types.test.ts | 6 +- packages/core/test/transaction.test.ts | 141 ++++---- packages/core/test/utils/connection.fake.ts | 69 ++-- 12 files changed, 541 insertions(+), 514 deletions(-) diff --git a/packages/core/test/auth.test.ts b/packages/core/test/auth.test.ts index 22f35e1d3..005450a70 100644 --- a/packages/core/test/auth.test.ts +++ b/packages/core/test/auth.test.ts @@ -19,7 +19,6 @@ import auth from '../src/auth' describe('auth', () => { - test('.bearer()', () => { expect(auth.bearer('==Qyahiadakkda')).toEqual({ scheme: 'bearer', credentials: '==Qyahiadakkda' }) }) diff --git a/packages/core/test/driver.test.ts b/packages/core/test/driver.test.ts index ef956eff4..c465167c8 100644 --- a/packages/core/test/driver.test.ts +++ b/packages/core/test/driver.test.ts @@ -16,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable @typescript-eslint/promise-function-async */ import { ConnectionProvider, newError, ServerInfo, Session } from '../src' import Driver, { READ } from '../src/driver' import { Bookmarks } from '../src/internal/bookmarks' @@ -47,26 +48,24 @@ describe('Driver', () => { }) afterEach(async () => { - if (driver) { + if (driver != null) { await driver.close() driver = null } }) - describe('.session()', () => { it('should create the session with impersonated user', () => { const impersonatedUser = 'the impostor' - const session = driver!.session({ impersonatedUser }) + const session = driver?.session({ impersonatedUser }) expect(session).not.toBeUndefined() expect(createSession).toHaveBeenCalledWith(expectedSessionParams({ impersonatedUser })) }) - it('should create the session without impersonated user', () => { - const session = driver!.session() + const session = driver?.session() expect(session).not.toBeUndefined() expect(createSession).toHaveBeenCalledWith(expectedSessionParams()) @@ -77,12 +76,12 @@ describe('Driver', () => { [null, Bookmarks.empty()], ['bookmark', new Bookmarks('bookmark')], [['bookmark'], new Bookmarks(['bookmark'])], - [['bookmark1', 'bookmark2'], new Bookmarks(['bookmark1', 'bookmark2'])], + [['bookmark1', 'bookmark2'], new Bookmarks(['bookmark1', 'bookmark2'])] ])('should create session using param bookmarks', (bookmarks, expectedBookmarks) => { - // @ts-ignore - const session = driver!.session({ bookmarks }) + // @ts-expect-error + const session = driver?.session({ bookmarks }) - expect(session.lastBookmarks()).toEqual(expectedBookmarks.values()) + expect(session?.lastBookmarks()).toEqual(expectedBookmarks.values()) }) }) @@ -96,11 +95,11 @@ describe('Driver', () => { ])('.supportsMultiDb() => %s', (_, expectedPromise) => { connectionProvider.supportsMultiDb = jest.fn(() => expectedPromise) - const promise: Promise = driver!.supportsMultiDb() + const promise: Promise | undefined = driver?.supportsMultiDb() expect(promise).toBe(expectedPromise) - promise.catch(_ => 'Do nothing').finally(() => {}) + promise?.catch(_ => 'Do nothing').finally(() => {}) }) it.each([ @@ -115,11 +114,11 @@ describe('Driver', () => { () => expectedPromise ) - const promise: Promise = driver!.supportsTransactionConfig() + const promise: Promise | undefined = driver?.supportsTransactionConfig() expect(promise).toBe(expectedPromise) - promise.catch(_ => 'Do nothing').finally(() => {}) + promise?.catch(_ => 'Do nothing').finally(() => {}) }) it.each([ @@ -134,11 +133,11 @@ describe('Driver', () => { () => expectedPromise ) - const promise: Promise = driver!.supportsUserImpersonation() + const promise: Promise | undefined = driver?.supportsUserImpersonation() expect(promise).toBe(expectedPromise) - promise.catch(_ => 'Do nothing').finally(() => {}) + promise?.catch(_ => 'Do nothing').finally(() => {}) }) it.each([ @@ -146,11 +145,11 @@ describe('Driver', () => { [{ encrypted: false }, false], [{}, false], [{ encrypted: 'ENCRYPTION_ON' }, true], - [{ encrypted: 'ENCRYPTION_OFF' }, false], + [{ encrypted: 'ENCRYPTION_OFF' }, false] ])('.isEncrypted()', (config, expectedValue) => { const connectionProvider = new ConnectionProvider() connectionProvider.close = jest.fn(() => Promise.resolve()) - // @ts-ignore + // @ts-expect-error const driver = new Driver(META_INFO, config, mockCreateConnectonProvider(connectionProvider)) expect(driver.isEncrypted()).toEqual(expectedValue) @@ -170,7 +169,7 @@ describe('Driver', () => { // No connection timeouts should be considered valid, since it means // the user doesn't case about the connection timeout at all. [{ connectionTimeout: 0, connectionAcquisitionTimeout: 2000 }, true], - [{ connectionTimeout: -1, connectionAcquisitionTimeout: 2000 }, true], + [{ connectionTimeout: -1, connectionAcquisitionTimeout: 2000 }, true] ])('should emit warning if `connectionAcquisitionTimeout` and `connectionTimeout` are conflicting. [%o} ', async (config, valid) => { const logging = { level: 'warn' as LogLevel, @@ -202,17 +201,17 @@ describe('Driver', () => { [{ database: undefined }, 'Promise.resolve(ServerInfo>)', Promise.resolve(new ServerInfo())], [{ database: undefined }, 'Promise.reject(Error)', Promise.reject(newError('something went wrong'))], [{ database: 'db' }, 'Promise.resolve(ServerInfo>)', Promise.resolve(new ServerInfo())], - [{ database: 'db' }, 'Promise.reject(Error)', Promise.reject(newError('something went wrong'))], + [{ database: 'db' }, 'Promise.reject(Error)', Promise.reject(newError('something went wrong'))] ])('.verifyConnectivity(%o) => %s', (input: { database?: string } | undefined, _, expectedPromise) => { connectionProvider.verifyConnectivityAndGetServerInfo = jest.fn(() => expectedPromise) - const promise: Promise = driver!.verifyConnectivity(input) + const promise: Promise | undefined = driver?.verifyConnectivity(input) expect(promise).toBe(expectedPromise) expect(connectionProvider.verifyConnectivityAndGetServerInfo) - .toBeCalledWith({ database: input && input.database ? input.database : '', accessMode: READ }) + .toBeCalledWith({ database: input?.database ?? '', accessMode: READ }) - promise.catch(_ => 'Do nothing').finally(() => { }) + promise?.catch(_ => 'Do nothing').finally(() => { }) }) it.each([ @@ -223,20 +222,20 @@ describe('Driver', () => { [{ database: undefined }, 'Promise.resolve(ServerInfo>)', Promise.resolve(new ServerInfo())], [{ database: undefined }, 'Promise.reject(Error)', Promise.reject(newError('something went wrong'))], [{ database: 'db' }, 'Promise.resolve(ServerInfo>)', Promise.resolve(new ServerInfo())], - [{ database: 'db' }, 'Promise.reject(Error)', Promise.reject(newError('something went wrong'))], + [{ database: 'db' }, 'Promise.reject(Error)', Promise.reject(newError('something went wrong'))] ])('.getServerInfo(%o) => %s', (input: { database?: string } | undefined, _, expectedPromise) => { connectionProvider.verifyConnectivityAndGetServerInfo = jest.fn(() => expectedPromise) - const promise: Promise = driver!.getServerInfo(input) + const promise: Promise | undefined = driver?.getServerInfo(input) expect(promise).toBe(expectedPromise) expect(connectionProvider.verifyConnectivityAndGetServerInfo) - .toBeCalledWith({ database: input && input.database ? input.database : '', accessMode: READ }) + .toBeCalledWith({ database: input?.database ?? '', accessMode: READ }) - promise.catch(_ => 'Do nothing').finally(() => { }) + promise?.catch(_ => 'Do nothing').finally(() => { }) }) - function mockCreateConnectonProvider(connectionProvider: ConnectionProvider) { + function mockCreateConnectonProvider (connectionProvider: ConnectionProvider) { return ( id: number, config: Object, @@ -245,7 +244,7 @@ describe('Driver', () => { ) => connectionProvider } - function expectedSessionParams(extra: any = {}) { + function expectedSessionParams (extra: any = {}): any { return { bookmarks: Bookmarks.empty(), config: { @@ -253,12 +252,12 @@ describe('Driver', () => { fetchSize: 1000, maxConnectionLifetime: 3600000, maxConnectionPoolSize: 100, - connectionTimeout: 30000, + connectionTimeout: 30000 }, connectionProvider, database: '', fetchSize: 1000, - mode: "WRITE", + mode: 'WRITE', reactive: false, impersonatedUser: undefined, ...extra diff --git a/packages/core/test/error.test.ts b/packages/core/test/error.test.ts index 36b2ba204..9e7ab7087 100644 --- a/packages/core/test/error.test.ts +++ b/packages/core/test/error.test.ts @@ -46,15 +46,13 @@ describe('newError', () => { }) describe('isRetriableError()', () => { - it.each(getRetriableErrorsFixture()) - ('should return true for error with code %s', error => { - expect(isRetriableError(error)).toBe(true) - }) + it.each(getRetriableErrorsFixture())('should return true for error with code %s', error => { + expect(isRetriableError(error)).toBe(true) + }) - it.each(getNonRetriableErrorsFixture()) - ('should return false for error with code %s', error => { - expect(isRetriableError(error)).toBe(false) - }) + it.each(getNonRetriableErrorsFixture())('should return false for error with code %s', error => { + expect(isRetriableError(error)).toBe(false) + }) }) describe('Neo4jError', () => { @@ -90,38 +88,34 @@ describe('Neo4jError', () => { expect(error.constructor).toEqual(Neo4jError) }) - test.each(getRetriableCodes()) - ('should define retriable as true for error with code %s', code => { - const error = new Neo4jError('message', code) + test.each(getRetriableCodes())('should define retriable as true for error with code %s', code => { + const error = new Neo4jError('message', code) - expect(error.retriable).toBe(true) - }) + expect(error.retriable).toBe(true) + }) - test.each(getNonRetriableCodes()) - ('should define retriable as false for error with code %s', code => { - const error = new Neo4jError('message', code) + test.each(getNonRetriableCodes())('should define retriable as false for error with code %s', code => { + const error = new Neo4jError('message', code) - expect(error.retriable).toBe(false) - }) + expect(error.retriable).toBe(false) + }) describe('.isRetriable()', () => { - it.each(getRetriableErrorsFixture()) - ('should return true for error with code %s', error => { - expect(Neo4jError.isRetriable(error)).toBe(true) - }) - - it.each(getNonRetriableErrorsFixture()) - ('should return false for error with code %s', error => { - expect(Neo4jError.isRetriable(error)).toBe(false) - }) + it.each(getRetriableErrorsFixture())('should return true for error with code %s', error => { + expect(Neo4jError.isRetriable(error)).toBe(true) + }) + + it.each(getNonRetriableErrorsFixture())('should return false for error with code %s', error => { + expect(Neo4jError.isRetriable(error)).toBe(false) + }) }) }) -function getRetriableErrorsFixture () { +function getRetriableErrorsFixture (): Array<[Neo4jError]> { return getRetriableCodes().map(code => [newError('message', code)]) } -function getNonRetriableErrorsFixture () { +function getNonRetriableErrorsFixture (): any[] { return [ null, undefined, @@ -132,7 +126,7 @@ function getNonRetriableErrorsFixture () { ] } -function getRetriableCodes () { +function getRetriableCodes (): string[] { return [ SERVICE_UNAVAILABLE, SESSION_EXPIRED, @@ -142,7 +136,7 @@ function getRetriableCodes () { ] } -function getNonRetriableCodes () { +function getNonRetriableCodes (): string[] { return [ 'Neo.TransientError.Transaction.Terminated', 'Neo.DatabaseError.General.UnknownError', diff --git a/packages/core/test/graph-types.test.ts b/packages/core/test/graph-types.test.ts index d991837d0..0dfbc7b9a 100644 --- a/packages/core/test/graph-types.test.ts +++ b/packages/core/test/graph-types.test.ts @@ -16,13 +16,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { +import { Node, isNode, Relationship, isRelationship, UnboundRelationship, - isUnboundRelationship, + isUnboundRelationship } from '../src/graph-types' import { @@ -68,7 +68,7 @@ describe('Node', () => { test.each(validNodes())('should be serialized as string', node => { expect(node.toString()).toMatchSnapshot() - }) + }) test.each(validNodes())('should be consider a node', (node: any) => { expect(isNode(node)).toBe(true) @@ -78,30 +78,30 @@ describe('Node', () => { expect(isNode(nonNode)).toBe(false) }) - function validNodes(): any[] { + function validNodes (): any[] { return [ [new Node(1, ['label'], {}, 'elementId')], [new Node(1, ['label'], {})], [new Node(1, [], {})], [new Node(BigInt(2), ['label'], {})], [new Node(int(3), ['label'], {})], - [new Node(1, [], { 'property': 'value' })], - [new Node(1, ['label'], { 'property': 'value' })], + [new Node(1, [], { property: 'value' })], + [new Node(1, ['label'], { property: 'value' })] ] } - function nonNodes(): any[] { + function nonNodes (): any[] { return [ [undefined], [null], - [{ identity: 1, labels: ['label'], properties: { 'property': 'value' } }], - [{ identity: 1, labels: ['label'], properties: { 'property': 'value' }, elementId: 'elementId' }], + [{ identity: 1, labels: ['label'], properties: { property: 'value' } }], + [{ identity: 1, labels: ['label'], properties: { property: 'value' }, elementId: 'elementId' }], [{}], - [{ 'property': 'value' }], - [{ 'property': 'value', 'labels': ['label'] }], - [{ 'property': 'value', 'labels': ['label'], 'identity': 1 }], - [{ identity: BigInt(2), labels: ['label'], properties: { 'property': 'value' } }], - [{ identity: int(3), labels: ['label'], properties: { 'property': 'value' } }], + [{ property: 'value' }], + [{ property: 'value', labels: ['label'] }], + [{ property: 'value', labels: ['label'], identity: 1 }], + [{ identity: BigInt(2), labels: ['label'], properties: { property: 'value' } }], + [{ identity: int(3), labels: ['label'], properties: { property: 'value' } }] ] } }) @@ -132,9 +132,9 @@ describe('Relationship', () => { }) test('should have properties', () => { - const relationship = new Relationship(1, 2, 3, 'Rel', { 'property': 'value' }) + const relationship = new Relationship(1, 2, 3, 'Rel', { property: 'value' }) - expect(relationship.properties).toEqual({ 'property': 'value' }) + expect(relationship.properties).toEqual({ property: 'value' }) }) test('should have elementId', () => { @@ -142,7 +142,7 @@ describe('Relationship', () => { expect(relationship.elementId).toEqual('elementId') }) - + test.each( validIdentityAndExpectedElementIds() )('should default elementId to indentity when it is not set', (identity, expected) => { @@ -181,7 +181,7 @@ describe('Relationship', () => { test.each(validRelationships())('should be serialized as string', relationship => { expect(relationship.toString()).toMatchSnapshot() - }) + }) test.each(validRelationships())('should be consider a relationship', relationship => { expect(isRelationship(relationship)).toBe(true) @@ -197,9 +197,9 @@ describe('Relationship', () => { [new Relationship(1, 2, 3, 'Rel', {}, 'elementId', 'startNodeElementId')], [new Relationship(1, 2, 3, 'Rel', {}, 'elementId')], [new Relationship(1, 2, 3, 'Rel', {})], - [new Relationship(1, 2, 3, 'Rel', { 'property': 'value' })], + [new Relationship(1, 2, 3, 'Rel', { property: 'value' })], [new Relationship(BigInt(4), BigInt(5), BigInt(6), 'Rel', {})], - [new Relationship(int(6), int(7), int(8), 'Rel', {})], + [new Relationship(int(6), int(7), int(8), 'Rel', {})] ] } @@ -209,20 +209,32 @@ describe('Relationship', () => { [null], ['Relationship'], [{}], - [{ 'property': 'value' }], + [{ property: 'value' }], [{ - identity: 1, start: 2, end: 3, type: 'Rel', - properties: { 'property': 'value' } + identity: 1, + start: 2, + end: 3, + type: 'Rel', + properties: { property: 'value' } }], [{ - identity: 1, start: 2, end: 3, type: 'Rel', - properties: { 'property': 'value' }, elementId: 'elementId' + identity: 1, + start: 2, + end: 3, + type: 'Rel', + properties: { property: 'value' }, + elementId: 'elementId' }], [{ - identity: 1, start: 2, end: 3, type: 'Rel', - properties: { 'property': 'value' }, elementId: 'elementId', - startNodeElementId: 'startNodeElementId', endNodeElementId: 'endNodeElementId' - }], + identity: 1, + start: 2, + end: 3, + type: 'Rel', + properties: { property: 'value' }, + elementId: 'elementId', + startNodeElementId: 'startNodeElementId', + endNodeElementId: 'endNodeElementId' + }] ] } }) @@ -241,14 +253,14 @@ describe('UnboundRelationship', () => { }) test('should have properties', () => { - const relationship = new UnboundRelationship(1, 'Rel', { 'property': 'value' }) + const relationship = new UnboundRelationship(1, 'Rel', { property: 'value' }) - expect(relationship.properties).toEqual({ 'property': 'value' }) + expect(relationship.properties).toEqual({ property: 'value' }) }) test.each(validUnboundRelationships())('should be serialized as string', relationship => { expect(relationship.toString()).toMatchSnapshot() - }) + }) test.each(validUnboundRelationships())('should be consider a unbound relationship', relationship => { expect(isUnboundRelationship(relationship)).toBe(true) @@ -256,7 +268,7 @@ describe('UnboundRelationship', () => { test.each( nonUnboundRelationships() - )('should not consider a non-unbound relationship object as unbound relationship', nonUnboundRelationship => { + )('should not consider a non-unbound relationship object as unbound relationship', nonUnboundRelationship => { expect(isUnboundRelationship(nonUnboundRelationship)).toBe(false) }) @@ -266,11 +278,11 @@ describe('UnboundRelationship', () => { expect(rel.bind(startNode.identity, endNode.identity)) .toEqual( new Relationship( - rel.identity, - startNode.identity, - endNode.identity, - rel.type, - rel.properties, + rel.identity, + startNode.identity, + endNode.identity, + rel.type, + rel.properties, rel.elementId ) ) @@ -282,11 +294,11 @@ describe('UnboundRelationship', () => { expect(rel.bindTo(startNode, endNode)) .toEqual( new Relationship( - rel.identity, - startNode.identity, - endNode.identity, - rel.type, - rel.properties, + rel.identity, + startNode.identity, + endNode.identity, + rel.type, + rel.properties, rel.elementId, startNode.elementId, endNode.elementId @@ -298,9 +310,9 @@ describe('UnboundRelationship', () => { return [ [new UnboundRelationship(1, 'Rel', {}, 'elementId')], [new UnboundRelationship(1, 'Rel', {})], - [new UnboundRelationship(1, 'Rel', { 'property': 'value' })], - [new UnboundRelationship(BigInt(2), 'Rel', { 'property': 'value' })], - [new UnboundRelationship(int(3), 'Rel', { 'property': 'value' })], + [new UnboundRelationship(1, 'Rel', { property: 'value' })], + [new UnboundRelationship(BigInt(2), 'Rel', { property: 'value' })], + [new UnboundRelationship(int(3), 'Rel', { property: 'value' })] ] } @@ -310,25 +322,28 @@ describe('UnboundRelationship', () => { [null], ['Relationship'], [{}], - [{ 'property': 'value' }], + [{ property: 'value' }], [{ - identity: 1, type: 'Rel', - properties: { 'property': 'value' } + identity: 1, + type: 'Rel', + properties: { property: 'value' } }], [{ - identity: 1, type: 'Rel', - properties: { 'property': 'value' }, elementId: 'elementId' + identity: 1, + type: 'Rel', + properties: { property: 'value' }, + elementId: 'elementId' }] ] } - function bindUnboundRelationshipFixture (): any[] { + function bindUnboundRelationshipFixture (): any[] { return [ [new UnboundRelationship(0, 'Rel', {}), new Node(1, ['Node'], {}), new Node(2, ['Node'], {})], [new UnboundRelationship(0, 'Rel', {}, 'elementId'), new Node(1, ['Node'], {}), new Node(2, ['Node'], {})], [new UnboundRelationship(0, 'Rel', {}), new Node(1, ['Node'], {}, 'nodeElementId'), new Node(2, ['Node'], {})], [new UnboundRelationship(0, 'Rel', {}), new Node(1, ['Node'], {}, 'nodeElementId'), new Node(2, ['Node'], {}), 'nodeElementId2'], - [new UnboundRelationship(0, 'Rel', {}, 'elementId'), new Node(1, ['Node'], {}, 'nodeElementId'), new Node(2, ['Node'], {}), 'nodeElementId2'], + [new UnboundRelationship(0, 'Rel', {}, 'elementId'), new Node(1, ['Node'], {}, 'nodeElementId'), new Node(2, ['Node'], {}), 'nodeElementId2'] ] } }) @@ -337,6 +352,6 @@ function validIdentityAndExpectedElementIds (): any[] { return [ [10, '10'], [int(12), '12'], - [BigInt(32), '32'], + [BigInt(32), '32'] ] } diff --git a/packages/core/test/integer.test.ts b/packages/core/test/integer.test.ts index 32447e192..ec3b4b42d 100644 --- a/packages/core/test/integer.test.ts +++ b/packages/core/test/integer.test.ts @@ -16,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable @typescript-eslint/restrict-template-expressions */ import Integer, { int, isInt, @@ -92,25 +93,25 @@ describe('Integer', () => { ) forEachEqualsScenarios(({ input, expectedOutput }) => - test(`Integer(${input.integer}).equals(${input.other}) toEqual ${expectedOutput}`, () => + test(`Integer(${input.integer}).equals(${mayIntegerToString(input.other)}) toEqual ${expectedOutput}`, () => expect(input.integer.equals(input.other)).toEqual(expectedOutput)) ) forEachEqualsScenarios(({ input, expectedOutput }) => test(`Integer(${input.integer}).notEquals(${ - input.other + mayIntegerToString(input.other) }) toEqual ${!expectedOutput}`, () => expect(input.integer.notEquals(input.other)).toEqual(!expectedOutput)) ) forEachLessThanScenarios(({ input, expectedOutput }) => - test(`Integer(${input.integer}).lessThan(${input.other}) toEqual ${expectedOutput}`, () => + test(`Integer(${input.integer}).lessThan(${mayIntegerToString(input.other)}) toEqual ${expectedOutput}`, () => expect(input.integer.lessThan(input.other)).toEqual(expectedOutput)) ) forEachLessThanScenarios(({ input, expectedOutput }) => test(`Integer(${input.integer}).greaterThanOrEqual(${ - input.other + mayIntegerToString(input.other) }) toEqual ${!expectedOutput}`, () => expect(input.integer.greaterThanOrEqual(input.other)).toEqual( !expectedOutput @@ -118,7 +119,7 @@ describe('Integer', () => { ) forEachLessOrEqualThanScenarios(({ input, expectedOutput }) => - test(`Integer(${input.integer}).lessThanOrEqual(${input.other}) toEqual ${expectedOutput}`, () => + test(`Integer(${input.integer}).lessThanOrEqual(${mayIntegerToString(input.other)}) toEqual ${expectedOutput}`, () => expect(input.integer.lessThanOrEqual(input.other)).toEqual( expectedOutput )) @@ -126,7 +127,7 @@ describe('Integer', () => { forEachLessOrEqualThanScenarios(({ input, expectedOutput }) => test(`Integer(${input.integer}).greaterThan(${ - input.other + mayIntegerToString(input.other) }) toEqual ${!expectedOutput}`, () => expect(input.integer.greaterThan(input.other)).toEqual(!expectedOutput)) ) @@ -137,22 +138,22 @@ describe('Integer', () => { ) forEachAddScenarios(({ input, expectedOutput }) => - test(`Integer(${input.integer}).add(${input.other}) toEqual ${expectedOutput}`, () => + test(`Integer(${input.integer}).add(${mayIntegerToString(input.other)}) toEqual ${expectedOutput}`, () => expect(input.integer.add(input.other)).toEqual(expectedOutput)) ) forEachSubtractScenarios(({ input, expectedOutput }) => - test(`Integer(${input.integer}).subtract(${input.other}) toEqual ${expectedOutput}`, () => + test(`Integer(${input.integer}).subtract(${mayIntegerToString(input.other)}) toEqual ${expectedOutput}`, () => expect(input.integer.subtract(input.other)).toEqual(expectedOutput)) ) forEachMultiplyScenarios(({ input, expectedOutput }) => - test(`Integer(${input.integer}).multiply(${input.other}) toEqual ${expectedOutput}`, () => + test(`Integer(${input.integer}).multiply(${mayIntegerToString(input.other)}) toEqual ${expectedOutput}`, () => expect(input.integer.multiply(input.other)).toEqual(expectedOutput)) ) forEachDivScenarios(({ input, expectedOutput }) => - test(`Integer(${input.integer}).div(${input.other}) toEqual ${expectedOutput}`, () => + test(`Integer(${input.integer}).div(${mayIntegerToString(input.other)}) toEqual ${expectedOutput}`, () => expect(input.integer.div(input.other)).toEqual(expectedOutput)) ) @@ -256,27 +257,27 @@ describe('Integer', () => { )) forEachFromValueScenarios(({ input, expectedOutput }) => - test(`Integer.fromValue(${input}) toEqual ${expectedOutput}`, () => + test(`Integer.fromValue(${mayIntegerToString(input)}) toEqual ${expectedOutput}`, () => expect(Integer.fromValue(input)).toEqual(expectedOutput)) ) forEachFromValueScenarios(({ input, expectedOutput }) => - test(`int(${input}) toEqual ${expectedOutput}`, () => + test(`int(${mayIntegerToString(input)}) toEqual ${expectedOutput}`, () => expect(int(input)).toEqual(expectedOutput)) ) forEachStaticToNumberScenarios(({ input, expectedOutput }) => - test(`Integer.toNumber(${input}) toEqual ${expectedOutput}`, () => + test(`Integer.toNumber(${mayIntegerToString(input)}) toEqual ${expectedOutput}`, () => expect(Integer.toNumber(input)).toEqual(expectedOutput)) ) forEachStaticToNumberScenarios(({ input, expectedOutput }) => - test(`toNumber(${input}) toEqual ${expectedOutput}`, () => + test(`toNumber(${mayIntegerToString(input)}) toEqual ${expectedOutput}`, () => expect(toNumber(input)).toEqual(expectedOutput)) ) forEachStaticToStringScenarios(({ input, expectedOutput }) => - test(`Integer.toString(${input}) toEqual ${expectedOutput}`, () => + test(`Integer.toString(${mayIntegerToString(input)}) toEqual ${expectedOutput}`, () => expect(Integer.toString(input)).toEqual(expectedOutput)) ) @@ -291,12 +292,12 @@ describe('Integer', () => { )) forEachStaticToStringScenarios(({ input, expectedOutput }) => - test(`toString(${input}) toEqual ${expectedOutput}`, () => + test(`toString(${mayIntegerToString(input)}) toEqual ${expectedOutput}`, () => expect(toString(input)).toEqual(expectedOutput)) ) forEachStaticInSafeRangeScenarios(({ input, expectedOutput }) => - test(`inSafeRange(${input}) toEqual ${expectedOutput}`, () => + test(`inSafeRange(${mayIntegerToString(input)}) toEqual ${expectedOutput}`, () => expect(inSafeRange(input)).toEqual(expectedOutput)) ) @@ -307,9 +308,9 @@ describe('Integer', () => { }) }) -function forEachToNumberOrInfinityScenarios( +function forEachToNumberOrInfinityScenarios ( func: Consumer> -) { +): void { ;[ v('42', 42), v('4242', 4242), @@ -328,9 +329,9 @@ function forEachToNumberOrInfinityScenarios( ].forEach(func) } -function forEachToNumberScenarios( +function forEachToNumberScenarios ( func: Consumer> -) { +): void { ;[ v('42', 42), v('4242', 4242), @@ -359,9 +360,9 @@ function forEachToNumberScenarios( ].forEach(func) } -function forEachInSafeRangeScenarios( +function forEachInSafeRangeScenarios ( func: Consumer> -) { +): void { ;[ v(int('42'), true), v(int('4242'), true), @@ -375,7 +376,7 @@ function forEachInSafeRangeScenarios( ].forEach(func) } -function forEachToIntScenarios(func: Consumer>) { +function forEachToIntScenarios (func: Consumer>): void { ;[ v(new Integer(), 0), v(new Integer(13), 13), @@ -385,13 +386,13 @@ function forEachToIntScenarios(func: Consumer>) { ].forEach(func) } -function forEachToStringScenarios( - func: Consumer> -) { - function i( +function forEachToStringScenarios ( + func: Consumer> +): void { + function i ( integer: Integer, radix?: number - ): { integer: Integer; radix?: number } { + ): { integer: Integer, radix?: number } { return { integer, radix } } @@ -424,9 +425,9 @@ function forEachToStringScenarios( ].forEach(func) } -function forEachGetHighBitsScenarios( +function forEachGetHighBitsScenarios ( func: Consumer> -) { +): void { ;[ v(new Integer(), 0), v(new Integer(123), 0), @@ -437,9 +438,9 @@ function forEachGetHighBitsScenarios( ].forEach(func) } -function forEachGetLowBitsScenarios( +function forEachGetLowBitsScenarios ( func: Consumer> -) { +): void { ;[ v(new Integer(), 0), v(new Integer(123), 123), @@ -450,9 +451,9 @@ function forEachGetLowBitsScenarios( ].forEach(func) } -function forEachGetNumBitsAbsScenarios( +function forEachGetNumBitsAbsScenarios ( func: Consumer> -) { +): void { ;[ v(Integer.MIN_VALUE, 64), v(Integer.MAX_VALUE, 63), @@ -464,9 +465,9 @@ function forEachGetNumBitsAbsScenarios( ].forEach(func) } -function forEachIsZeroScenarios( +function forEachIsZeroScenarios ( func: Consumer> -) { +): void { ;[ v(Integer.MIN_VALUE, false), v(Integer.MAX_VALUE, false), @@ -478,9 +479,9 @@ function forEachIsZeroScenarios( ].forEach(func) } -function forEachIsNegativeScenarios( +function forEachIsNegativeScenarios ( func: Consumer> -) { +): void { ;[ v(Integer.MIN_VALUE, true), v(Integer.MAX_VALUE, false), @@ -494,9 +495,9 @@ function forEachIsNegativeScenarios( ].forEach(func) } -function forEachIsOddScenarios( +function forEachIsOddScenarios ( func: Consumer> -) { +): void { ;[ v(Integer.fromValue(1), true), v(Integer.fromValue(-1), true), @@ -510,13 +511,13 @@ function forEachIsOddScenarios( ].forEach(func) } -function forEachEqualsScenarios( - func: Consumer> -) { - function i( +function forEachEqualsScenarios ( + func: Consumer> +): void { + function i ( integer: Integer, - other: Interable - ): { integer: Integer; other: Interable } { + other: MayIntegerCompatible + ): { integer: Integer, other: MayIntegerCompatible } { return { integer, other } } ;[ @@ -531,13 +532,13 @@ function forEachEqualsScenarios( ].forEach(func) } -function forEachLessThanScenarios( - func: Consumer> -) { - function i( +function forEachLessThanScenarios ( + func: Consumer> +): void { + function i ( integer: Integer, - other: Interable - ): { integer: Integer; other: Interable } { + other: MayIntegerCompatible + ): { integer: Integer, other: MayIntegerCompatible } { return { integer, other } } ;[ @@ -560,13 +561,13 @@ function forEachLessThanScenarios( ].forEach(func) } -function forEachLessOrEqualThanScenarios( - func: Consumer> -) { - function i( +function forEachLessOrEqualThanScenarios ( + func: Consumer> +): void { + function i ( integer: Integer, - other: Interable - ): { integer: Integer; other: Interable } { + other: MayIntegerCompatible + ): { integer: Integer, other: MayIntegerCompatible } { return { integer, other } } ;[ @@ -589,9 +590,9 @@ function forEachLessOrEqualThanScenarios( ].forEach(func) } -function forEachNegateScenarios( +function forEachNegateScenarios ( func: Consumer> -) { +): void { ;[ v(Integer.fromValue(1), Integer.fromNumber(-1)), v(Integer.fromValue(-1), Integer.fromNumber(1)), @@ -604,13 +605,13 @@ function forEachNegateScenarios( ].forEach(func) } -function forEachAddScenarios( - func: Consumer> -) { - function i( +function forEachAddScenarios ( + func: Consumer> +): void { + function i ( integer: Integer, - other: Interable - ): { integer: Integer; other: Interable } { + other: MayIntegerCompatible + ): { integer: Integer, other: MayIntegerCompatible } { return { integer, other } } ;[ @@ -627,13 +628,13 @@ function forEachAddScenarios( ].forEach(func) } -function forEachSubtractScenarios( - func: Consumer> -) { - function i( +function forEachSubtractScenarios ( + func: Consumer> +): void { + function i ( integer: Integer, - other: Interable - ): { integer: Integer; other: Interable } { + other: MayIntegerCompatible + ): { integer: Integer, other: MayIntegerCompatible } { return { integer, other } } ;[ @@ -650,13 +651,13 @@ function forEachSubtractScenarios( ].forEach(func) } -function forEachMultiplyScenarios( - func: Consumer> -) { - function i( +function forEachMultiplyScenarios ( + func: Consumer> +): void { + function i ( integer: Integer, - other: Interable - ): { integer: Integer; other: Interable } { + other: MayIntegerCompatible + ): { integer: Integer, other: MayIntegerCompatible } { return { integer, other } } ;[ @@ -678,13 +679,13 @@ function forEachMultiplyScenarios( ].forEach(func) } -function forEachDivScenarios( - func: Consumer> -) { - function i( +function forEachDivScenarios ( + func: Consumer> +): void { + function i ( integer: Integer, - other: Interable - ): { integer: Integer; other: Interable } { + other: MayIntegerCompatible + ): { integer: Integer, other: MayIntegerCompatible } { return { integer, other } } ;[ @@ -706,18 +707,18 @@ function forEachDivScenarios( ].forEach(func) } -function forEachModuloScenarios( +function forEachModuloScenarios ( func: Consumer< - AssertionPair< - { dividend: Integer; divisor: number | string | Integer }, - Integer - > + AssertionPair< + { dividend: Integer, divisor: number | string | Integer }, + Integer > -) { - function d( + > +): void { + function d ( dividend: Integer, divisor: number | string | Integer - ): { dividend: Integer; divisor: number | string | Integer } { + ): { dividend: Integer, divisor: number | string | Integer } { return { dividend, divisor } } @@ -737,7 +738,7 @@ function forEachModuloScenarios( ].forEach(func) } -function forEachNotScenario(func: Consumer>) { +function forEachNotScenario (func: Consumer>): void { ;[ v( Integer.MIN_VALUE, @@ -754,18 +755,18 @@ function forEachNotScenario(func: Consumer>) { ].forEach(func) } -function forEachAndScenario( +function forEachAndScenario ( func: Consumer< - AssertionPair< - { integer: Integer; other: Integer | number | string }, - Integer - > + AssertionPair< + { integer: Integer, other: Integer | number | string }, + Integer + > > -) { - function a( +): void { + function a ( integer: Integer, other: Integer | number | string - ): { integer: Integer; other: Integer | number | string } { + ): { integer: Integer, other: Integer | number | string } { return { integer, other } } @@ -781,18 +782,18 @@ function forEachAndScenario( ].forEach(func) } -function forEachOrScenario( +function forEachOrScenario ( func: Consumer< - AssertionPair< - { integer: Integer; other: Integer | number | string }, - Integer - > + AssertionPair< + { integer: Integer, other: Integer | number | string }, + Integer + > > -) { - function a( +): void { + function a ( integer: Integer, other: Integer | number | string - ): { integer: Integer; other: Integer | number | string } { + ): { integer: Integer, other: Integer | number | string } { return { integer, other } } @@ -808,18 +809,18 @@ function forEachOrScenario( ].forEach(func) } -function forEachXorScenario( +function forEachXorScenario ( func: Consumer< - AssertionPair< - { integer: Integer; other: Integer | number | string }, - Integer - > + AssertionPair< + { integer: Integer, other: Integer | number | string }, + Integer > -) { - function a( + > +): void { + function a ( integer: Integer, other: Integer | number | string - ): { integer: Integer; other: Integer | number | string } { + ): { integer: Integer, other: Integer | number | string } { return { integer, other } } @@ -835,15 +836,15 @@ function forEachXorScenario( ].forEach(func) } -function forEachShiftLeftScenario( +function forEachShiftLeftScenario ( func: Consumer< - AssertionPair<{ integer: Integer; numBits: Integer | number }, Integer> + AssertionPair<{ integer: Integer, numBits: Integer | number }, Integer> > -) { - function s( +): void { + function s ( integer: Integer, numBits: Integer | number - ): { integer: Integer; numBits: Integer | number } { + ): { integer: Integer, numBits: Integer | number } { return { integer, numBits } } @@ -858,15 +859,15 @@ function forEachShiftLeftScenario( ].forEach(func) } -function forEachShiftRightScenario( +function forEachShiftRightScenario ( func: Consumer< - AssertionPair<{ integer: Integer; numBits: Integer | number }, Integer> + AssertionPair<{ integer: Integer, numBits: Integer | number }, Integer> > -) { - function s( +): void { + function s ( integer: Integer, numBits: Integer | number - ): { integer: Integer; numBits: Integer | number } { + ): { integer: Integer, numBits: Integer | number } { return { integer, numBits } } @@ -881,7 +882,7 @@ function forEachShiftRightScenario( ].forEach(func) } -function forEachIsIntegerScenario(func: Consumer>) { +function forEachIsIntegerScenario (func: Consumer>): void { ;[ v('42', false), v(42, false), @@ -901,9 +902,9 @@ function forEachIsIntegerScenario(func: Consumer>) { ].forEach(func) } -function forEachFromIntScenarios( +function forEachFromIntScenarios ( func: Consumer> -) { +): void { ;[ v(-128, new Integer(-128, -1)), v(127, new Integer(127, 0)), @@ -913,13 +914,13 @@ function forEachFromIntScenarios( ].forEach(func) } -function forEachFromBitsScenarios( - func: Consumer> -) { - function b( +function forEachFromBitsScenarios ( + func: Consumer> +): void { + function b ( lowBits: number, highBits: number - ): { lowBits: number; highBits: number } { + ): { lowBits: number, highBits: number } { return { lowBits, highBits } } @@ -930,9 +931,9 @@ function forEachFromBitsScenarios( ].forEach(func) } -function forEachFromNumberScenarios( +function forEachFromNumberScenarios ( func: Consumer> -) { +): void { const TWO_PWR_63: number = 9223372036854776000 ;[ v(-128, new Integer(-128, -1)), @@ -948,10 +949,10 @@ function forEachFromNumberScenarios( ].forEach(func) } -function forEachFromStringScenarios( - func: Consumer> -) { - function i(str: string, radix?: number): { str: string; radix?: number } { +function forEachFromStringScenarios ( + func: Consumer> +): void { + function i (str: string, radix?: number): { str: string, radix?: number } { return { str, radix } } @@ -989,15 +990,33 @@ function forEachFromStringScenarios( ].forEach(func) } -type Interable = +type MayIntegerCompatible = | Integer | number - | { low: number; high: number } + | { low: number, high: number } | string | bigint -function forEachFromValueScenarios( - func: Consumer> -) { + +function mayIntegerToString (val?: MayIntegerCompatible): string { + function isLowAndHigh (v: any): v is { low: number, high: number } { + const isNotObject = v instanceof Integer || v instanceof Number || v instanceof BigInt || v instanceof String + return !isNotObject + } + if (val === null) { + return 'null' + } + if (val === undefined) { + return 'undefined' + } + if (isLowAndHigh(val)) { + return val.low?.toString() + ',' + val.high?.toString() + } + return val.toString() +} + +function forEachFromValueScenarios ( + func: Consumer> +): void { ;[ v(Integer.ONE, Integer.ONE), v('1', Integer.ONE), @@ -1006,9 +1025,9 @@ function forEachFromValueScenarios( ].forEach(func) } -function forEachStaticToNumberScenarios( - func: Consumer> -) { +function forEachStaticToNumberScenarios ( + func: Consumer> +): void { ;[ v(Integer.ONE, 1), v('1', 1), @@ -1018,9 +1037,9 @@ function forEachStaticToNumberScenarios( ].forEach(func) } -function forEachStaticToStringScenarios( - func: Consumer> -) { +function forEachStaticToStringScenarios ( + func: Consumer> +): void { ;[ v(Integer.ONE, '1'), v('1', '1'), @@ -1029,9 +1048,9 @@ function forEachStaticToStringScenarios( ].forEach(func) } -function forEachStaticInSafeRangeScenarios( - func: Consumer> -) { +function forEachStaticInSafeRangeScenarios ( + func: Consumer> +): void { ;[ v(Integer.ONE, true), v('1', true), @@ -1039,8 +1058,10 @@ function forEachStaticInSafeRangeScenarios( v({ low: 1, high: 0 }, true), v(Integer.MAX_VALUE, false), v(Integer.MIN_VALUE, false), + // eslint-disable-next-line no-loss-of-precision v(99999191919191919191, false), v('99999191919191919191', false), + // eslint-disable-next-line no-loss-of-precision v({ low: 99999999181818811818, high: 191919111111991919 }, false) ].forEach(func) } @@ -1050,10 +1071,8 @@ interface AssertionPair { expectedOutput: O } -interface Consumer { - (i: I): void -} +type Consumer = (i: I) => void -function v(input: I, expectedOutput: O): AssertionPair { +function v (input: I, expectedOutput: O): AssertionPair { return { input, expectedOutput } } diff --git a/packages/core/test/internal/url-util.test.ts b/packages/core/test/internal/url-util.test.ts index 008ccfc29..953db2b8f 100644 --- a/packages/core/test/internal/url-util.test.ts +++ b/packages/core/test/internal/url-util.test.ts @@ -792,9 +792,9 @@ describe('#unit url-util', () => { }) }) - function verifyUrl(urlString: string, expectedUrl: PartialUrl) { + function verifyUrl (urlString: string, expectedUrl: PartialUrl): void { const url = parse(urlString) - if (expectedUrl.scheme) { + if (expectedUrl.scheme != null) { expect(url.scheme).toEqual(expectedUrl.scheme) } else { expect(url.scheme).toBeNull() @@ -804,36 +804,40 @@ describe('#unit url-util', () => { expect(url.host).not.toBeNull() expect(url.host).toEqual(expectedUrl.host) - if (expectedUrl.port) { + if (expectedUrl.port != null) { expect(url.port).toEqual(expectedUrl.port) } else { expect(url.port).toEqual( - urlUtil.defaultPortForScheme(expectedUrl.scheme!!) + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + urlUtil.defaultPortForScheme(expectedUrl.scheme!) ) } verifyHostAndPort(url, expectedUrl) - if (expectedUrl.query) { + if (expectedUrl.query != null) { expect(url.query).toEqual(expectedUrl.query) } else { expect(url.query).toEqual({}) } } - function verifyHostAndPort(url: urlUtil.Url, expectedUrl: PartialUrl) { + function verifyHostAndPort (url: urlUtil.Url, expectedUrl: PartialUrl): void { const port = - expectedUrl.port === 0 || expectedUrl.port + expectedUrl.port === 0 || expectedUrl.port != null ? expectedUrl.port - : urlUtil.defaultPortForScheme(expectedUrl.scheme!!) + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + : urlUtil.defaultPortForScheme(expectedUrl.scheme!) - if (expectedUrl.ipv6) { + if (expectedUrl.ipv6 != null) { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions expect(url.hostAndPort).toEqual(`[${expectedUrl.host}]:${port}`) } else { + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions expect(url.hostAndPort).toEqual(`${expectedUrl.host}:${port}`) } } - function parse(url: any): urlUtil.Url { + function parse (url: any): urlUtil.Url { return urlUtil.parseDatabaseUrl(url) } }) diff --git a/packages/core/test/record.test.ts b/packages/core/test/record.test.ts index 6555acfeb..5f903ddc1 100644 --- a/packages/core/test/record.test.ts +++ b/packages/core/test/record.test.ts @@ -103,7 +103,7 @@ describe('Record', () => { it('should allow forEach through the record', () => { // Given const record = new Record(['name', 'age'], ['Bob', 45]) - const result: [any, string, Record][] = [] + const result: Array<[any, string, Record]> = [] // When record.forEach((value, key, record) => { diff --git a/packages/core/test/result.test.ts b/packages/core/test/result.test.ts index c9b87e1e3..c772711ab 100644 --- a/packages/core/test/result.test.ts +++ b/packages/core/test/result.test.ts @@ -59,11 +59,11 @@ describe('Result', () => { expect(keys).toBe(expectedKeys) }) - it('should reject pre-existing errors', () => { + it('should reject pre-existing errors', async () => { const expectedError = newError('some error') streamObserverMock.onError(expectedError) - expect(result.keys()).rejects.toBe(expectedError) + await expect(result.keys()).rejects.toBe(expectedError) }) it('should reject already consumed pre-existing error', async () => { @@ -76,7 +76,7 @@ describe('Result', () => { // ignore } - expect(result.keys()).rejects.toBe(expectedError) + await expect(result.keys()).rejects.toBe(expectedError) }) it('should resolve key pushed afterwards', done => { @@ -86,7 +86,7 @@ describe('Result', () => { expect(keys).toBe(expectedKeys) done() - }) + }).catch(done) streamObserverMock.onKeys(expectedKeys) }) @@ -174,11 +174,11 @@ describe('Result', () => { expect(summary).toEqual(expectedSummary) }) - it('should reject a pre-existing error', () => { + it('should reject a pre-existing error', async () => { const expectedError = newError('the expected error') streamObserverMock.onError(expectedError) - expect(result.summary()).rejects.toThrow(expectedError) + await expect(result.summary()).rejects.toThrow(expectedError) }) it('should reject already consumed pre-existing error', async () => { @@ -191,7 +191,7 @@ describe('Result', () => { // ignore } - expect(result.summary()).rejects.toThrow(expectedError) + await expect(result.summary()).rejects.toThrow(expectedError) }) it('should resolve summary pushe afterwards', done => { @@ -233,7 +233,7 @@ describe('Result', () => { let receivedKeys: string[] = [] await result.subscribe({ - onKeys(keys) { + onKeys (keys) { receivedKeys = keys } }) @@ -252,7 +252,7 @@ describe('Result', () => { streamObserverMock.onNext(rawRecord2) await result.subscribe({ - onNext(record) { + onNext (record) { receivedRecords.push(record) } }) @@ -296,8 +296,8 @@ describe('Result', () => { streamObserverMock.onCompleted(metadata) const promiseSummary = new Promise( - async resolve => - await result.subscribe({ + resolve => + result.subscribe({ onCompleted: resolve }) ) @@ -314,8 +314,8 @@ describe('Result', () => { streamObserverMock.onError(error) const promiseError = new Promise( - async resolve => - await result.subscribe({ + resolve => + result.subscribe({ onError: resolve }) ) @@ -349,8 +349,8 @@ describe('Result', () => { streamObserverMock.onError(error) const promiseError = new Promise( - async resolve => - await result.subscribe({ + resolve => + result.subscribe({ onError: resolve }) ) @@ -376,8 +376,8 @@ describe('Result', () => { streamObserverMock.onCompleted(metadata) const promiseSummary = new Promise( - async resolve => - await result.subscribe({ + resolve => + result.subscribe({ onCompleted: resolve }) ) @@ -397,8 +397,8 @@ describe('Result', () => { } } - connectionHolderMock.getConnection = (): Promise => { - return Promise.resolve(asConnection(connectionMock)) + connectionHolderMock.getConnection = async (): Promise => { + return asConnection(connectionMock) } const metadata = { resultConsumedAfter: 20, @@ -415,8 +415,8 @@ describe('Result', () => { streamObserverMock.onCompleted(metadata) const promiseSummary = new Promise( - async resolve => - await result.subscribe({ + resolve => + result.subscribe({ onCompleted: resolve }) ) @@ -571,8 +571,8 @@ describe('Result', () => { } } - connectionHolderMock.getConnection = (): Promise => { - return Promise.resolve(asConnection(connectionMock)) + connectionHolderMock.getConnection = async (): Promise => { + return await Promise.resolve(asConnection(connectionMock)) } const metadata = { resultConsumedAfter: 20, @@ -601,6 +601,7 @@ describe('Result', () => { const subscribe = jest.spyOn(streamObserverMock, 'subscribe') streamObserverMock.onCompleted({}) + // eslint-disable-next-line @typescript-eslint/no-unused-vars for await (const _ of result) { // do nothing } @@ -612,7 +613,7 @@ describe('Result', () => { const pause = jest.spyOn(streamObserverMock, 'pause') const resume = jest.spyOn(streamObserverMock, 'resume') streamObserverMock.onCompleted({}) - + // eslint-disable-next-line @typescript-eslint/no-unused-vars for await (const _ of result) { // do nothing } @@ -628,6 +629,7 @@ describe('Result', () => { const pause = jest.spyOn(streamObserverMock, 'pause') streamObserverMock.onCompleted({}) + // eslint-disable-next-line @typescript-eslint/no-unused-vars for await (const _ of result) { // do nothing } @@ -847,7 +849,7 @@ describe('Result', () => { for await (const record of res) { records.push(record) - await new Promise(r => setTimeout(r, 0.1)) + await new Promise(resolve => setTimeout(resolve, 0.1)) } expect(records).toEqual([ @@ -862,13 +864,14 @@ describe('Result', () => { it.each([ ['success', async (stream: any) => stream.onCompleted({})], - ['error', async (stream: any) => stream.onError(new Error('error'))], - ])('should thrown on iterating over an consumed result [%s]', async(_, completeStream) => { - completeStream(streamObserverMock) + ['error', async (stream: any) => stream.onError(new Error('error'))] + ])('should thrown on iterating over an consumed result [%s]', async (_, completeStream) => { + await completeStream(streamObserverMock) await result.summary().catch(() => {}) try { + // eslint-disable-next-line @typescript-eslint/no-unused-vars for await (const _ of result) { expect('not to iterate over consumed result').toBe(true) } @@ -893,6 +896,7 @@ describe('Result', () => { const it = result[Symbol.asyncIterator]() await it.next() + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { value, done } = await it.return!(summary) expect(value).toEqual(summary) @@ -911,6 +915,7 @@ describe('Result', () => { const it = result[Symbol.asyncIterator]() await it.next() + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion await it.return!(new ResultSummary('query', {}, {})) const { value, done } = await it.next() @@ -924,6 +929,7 @@ describe('Result', () => { const it = result[Symbol.asyncIterator]() + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion await it.return!(new ResultSummary('query', {}, {})) await it.next() @@ -936,6 +942,7 @@ describe('Result', () => { const it = result[Symbol.asyncIterator]() + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion await it.return!(new ResultSummary('query', {}, {})) await it.next() @@ -953,13 +960,12 @@ describe('Result', () => { streamObserverMock.onNext(rawRecord1) streamObserverMock.onNext(rawRecord2) - const it = result[Symbol.asyncIterator]() await it.next() + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion await it.return!(new ResultSummary('query', {}, {})) - expect(cancel).toBeCalled() }) @@ -968,6 +974,7 @@ describe('Result', () => { const it = result[Symbol.asyncIterator]() + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion await it.return!(new ResultSummary('query', {}, {})) await it.next() @@ -979,6 +986,7 @@ describe('Result', () => { const it = result[Symbol.asyncIterator]() + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion await it.return!(new ResultSummary('query', {}, {})) await it.peek() @@ -1041,7 +1049,6 @@ describe('Result', () => { expect(resume).toBeCalledTimes(1) }) - it('should return the first record', async () => { const keys = ['a', 'b'] const rawRecord1 = [1, 2] @@ -1181,7 +1188,6 @@ describe('Result', () => { new Record(keys, rawRecord1), new Record(keys, rawRecord2) ]) - }) it('should throws it when it is the event after onKeys', async () => { @@ -1228,15 +1234,18 @@ describe('Result', () => { describe('.isOpen()', () => { it('should return true when the stream is open', async () => { - await result._subscribe({}).catch(() => {}) - + await result._subscribe({}) + expect(result.isOpen()).toBe(true) }) it('should return false when the stream is closed', async () => { streamObserverMock.onCompleted({}) - await result._subscribe({}).catch(() => {}) + await new Promise((resolve) => result.subscribe({ + onCompleted: resolve, + onError: resolve + })) expect(result.isOpen()).toBe(false) }) @@ -1381,9 +1390,9 @@ describe('Result', () => { describe.each([ [ 'Promise.resolve(new observer.FailedObserver({ error: expectedError }))', - () => Promise.resolve(new observer.FailedObserver({ error: expectedError })) + async () => await Promise.resolve(new observer.FailedObserver({ error: expectedError })) ], - ['Promise.reject(expectedError)', () => Promise.reject(expectedError)] + ['Promise.reject(expectedError)', async () => await Promise.reject(expectedError)] ])('new Result(%s, "query") ', (_, getPromise) => { let result: Result @@ -1392,11 +1401,11 @@ describe('Result', () => { }) describe('.keys()', () => { - shouldReturnRejectedPromiseWithTheExpectedError(() => result.keys()) + shouldReturnRejectedPromiseWithTheExpectedError(async () => await result.keys()) }) describe('.summary()', () => { - shouldReturnRejectedPromiseWithTheExpectedError(() => result.summary()) + shouldReturnRejectedPromiseWithTheExpectedError(async () => await result.summary()) }) describe('Promise', () => { @@ -1425,6 +1434,7 @@ describe('Result', () => { describe('asyncIterator', () => { shouldReturnRejectedPromiseWithTheExpectedError(async () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars for await (const _ of result) { // do nothing } @@ -1451,7 +1461,7 @@ describe('Result', () => { it('should be false after any interactio with the stream', async () => { const it = result[Symbol.asyncIterator]() - + try { await it.next() } catch (error) { @@ -1462,67 +1472,71 @@ describe('Result', () => { }) }) - function shouldReturnRejectedPromiseWithTheExpectedError( + function shouldReturnRejectedPromiseWithTheExpectedError ( supplier: () => Promise - ) { - it('should return rejected promise with the expected error', () => - expect(supplier()).rejects.toBe(expectedError)) + ): void { + it('should return rejected promise with the expected error', async () => + await expect(supplier()).rejects.toBe(expectedError)) } }) }) class ResultStreamObserverMock implements observer.ResultStreamObserver { - private _queuedRecords: Record[] + private readonly _queuedRecords: Record[] private _fieldKeys?: string[] - private _observers: ResultObserver[] + private readonly _observers: ResultObserver[] private _error?: Error private _meta?: any - constructor() { + constructor () { this._queuedRecords = [] this._observers = [] } - cancel(): void {} + cancel (): void {} - prepareToHandleSingleResponse(): void {} + prepareToHandleSingleResponse (): void {} - markCompleted(): void {} + markCompleted (): void {} - subscribe(observer: ResultObserver): void { + subscribe (observer: ResultObserver): void { this._observers.push(observer) - if (observer.onError && this._error) { - observer.onError!(this._error) + if ((observer.onError != null) && (this._error != null)) { + observer.onError(this._error) return } - if (observer.onKeys && this._fieldKeys) { - observer.onKeys!(this._fieldKeys) + if ((observer.onKeys != null) && (this._fieldKeys != null)) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + observer.onKeys(this._fieldKeys) } - if (observer.onNext) { + if (observer.onNext != null) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this._queuedRecords.forEach(record => observer.onNext!(record)) } - if (observer.onCompleted && this._meta) { - observer.onCompleted!(this._meta) + if ((observer.onCompleted != null) && this._meta != null) { + observer.onCompleted(this._meta) } } - onKeys(keys: string[]) { + onKeys (keys: string[]): void { this._fieldKeys = keys this._observers.forEach(o => { - if (o.onKeys) { - o.onKeys!(keys) + if (o.onKeys != null) { + o.onKeys(keys) } }) } - onNext(rawRecord: any[]) { + onNext (rawRecord: any[]): void { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const record = new Record(this._fieldKeys!, rawRecord) const streamed = this._observers .filter(o => o.onNext) + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion .map(o => o.onNext!(record)) .reduce(() => true, false) @@ -1531,15 +1545,17 @@ class ResultStreamObserverMock implements observer.ResultStreamObserver { } } - onError(error: Error) { + onError (error: Error): void { this._error = error + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this._observers.filter(o => o.onError).forEach(o => o.onError!(error)) } - onCompleted(meta: any) { + onCompleted (meta: any): void { this._meta = meta this._observers .filter(o => o.onCompleted) + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion .forEach(o => o.onCompleted!(meta)) } @@ -1547,17 +1563,17 @@ class ResultStreamObserverMock implements observer.ResultStreamObserver { // do nothing } - resume(): void { + resume (): void { // do nothing } } -function simulateStream( +function simulateStream ( records: any[][], observer: ResultStreamObserverMock, fetchSize: number, timeout: number = 1): { - resume: () => void, + resume: () => void pause: () => void } { const state = { @@ -1567,7 +1583,7 @@ function simulateStream( consumed: 0 } - const streaming = () => { + const streaming = (): void => { if (state.streaming || state.finished) { return } @@ -1597,7 +1613,6 @@ function simulateStream( observer.onNext(record) } state.consumed++ - }, timeout) } @@ -1613,13 +1628,12 @@ function simulateStream( /* return () => { - - + return true } */ } -function asConnection(value: any): Connection { +function asConnection (value: any): Connection { return value } diff --git a/packages/core/test/session.test.ts b/packages/core/test/session.test.ts index a975b13e7..19cbc9cd3 100644 --- a/packages/core/test/session.test.ts +++ b/packages/core/test/session.test.ts @@ -27,7 +27,7 @@ describe('session', () => { const connection = newFakeConnection() const session = newSessionWithConnection(connection) - session.close().then(() => done()) + session.close().then(() => done()).catch(done) }, 70000) it('close should return promise even when already closed ', done => { @@ -38,9 +38,9 @@ describe('session', () => { session.close().then(() => { session.close().then(() => { done() - }) - }) - }) + }).catch(done) + }).catch(done) + }).catch(done) }, 70000) it('run should send watermarks to Result when fetchsize if defined', async () => { @@ -48,14 +48,14 @@ describe('session', () => { const session = newSessionWithConnection(connection, false, 1000) const result = session.run('RETURN 1') - await result; + await result expect(connection.seenProtocolOptions[0]).toMatchObject({ fetchSize: 1000, lowRecordWatermark: 300, highRecordWatermark: 700 }) - // @ts-ignore + // @ts-expect-error expect(result._watermarks).toEqual({ high: 700, low: 300 }) }) @@ -64,7 +64,7 @@ describe('session', () => { const session = newSessionWithConnection(connection, false, FETCH_ALL) const result = session.run('RETURN 1') - await result; + await result expect(connection.seenProtocolOptions[0]).toMatchObject({ fetchSize: FETCH_ALL, @@ -72,7 +72,7 @@ describe('session', () => { highRecordWatermark: Number.MAX_VALUE }) - // @ts-ignore + // @ts-expect-error expect(result._watermarks).toEqual({ high: Number.MAX_VALUE, low: Number.MAX_VALUE }) }) @@ -82,9 +82,9 @@ describe('session', () => { const tx = session.beginTransaction() - // @ts-ignore + // @ts-expect-error expect(tx._lowRecordWatermak).toEqual(300) - // @ts-ignore + // @ts-expect-error expect(tx._highRecordWatermark).toEqual(700) }) @@ -92,12 +92,11 @@ describe('session', () => { const connection = newFakeConnection() const session = newSessionWithConnection(connection, false, FETCH_ALL) - const tx = session.beginTransaction() - // @ts-ignore + // @ts-expect-error expect(tx._lowRecordWatermak).toEqual(Number.MAX_VALUE) - // @ts-ignore + // @ts-expect-error expect(tx._highRecordWatermark).toEqual(Number.MAX_VALUE) }) @@ -107,9 +106,9 @@ describe('session', () => { const status = { functionCalled: false } await session.writeTransaction(tx => { - // @ts-ignore + // @ts-expect-error expect(tx._lowRecordWatermak).toEqual(300) - // @ts-ignore + // @ts-expect-error expect(tx._highRecordWatermark).toEqual(700) status.functionCalled = true @@ -124,9 +123,9 @@ describe('session', () => { const status = { functionCalled: false } await session.writeTransaction(tx => { - // @ts-ignore + // @ts-expect-error expect(tx._lowRecordWatermak).toEqual(Number.MAX_VALUE) - // @ts-ignore + // @ts-expect-error expect(tx._highRecordWatermark).toEqual(Number.MAX_VALUE) status.functionCalled = true @@ -141,9 +140,9 @@ describe('session', () => { const status = { functionCalled: false } await session.readTransaction(tx => { - // @ts-ignore + // @ts-expect-error expect(tx._lowRecordWatermak).toEqual(300) - // @ts-ignore + // @ts-expect-error expect(tx._highRecordWatermark).toEqual(700) status.functionCalled = true @@ -158,9 +157,9 @@ describe('session', () => { const status = { functionCalled: false } await session.readTransaction(tx => { - // @ts-ignore + // @ts-expect-error expect(tx._lowRecordWatermak).toEqual(Number.MAX_VALUE) - // @ts-ignore + // @ts-expect-error expect(tx._highRecordWatermark).toEqual(Number.MAX_VALUE) status.functionCalled = true @@ -182,16 +181,16 @@ describe('session', () => { session.close().then(() => { expect(connection.isReleasedOnce()).toBeTruthy() done() - }) - }) - }) + }).catch(done) + }).catch(done) + }).catch(done) }, 70000) it('should close transaction executor', done => { const session = newSessionWithConnection(newFakeConnection()) let closeCalledTimes = 0 - // @ts-ignore + // @ts-expect-error const transactionExecutor = session._transactionExecutor const originalClose = transactionExecutor.close transactionExecutor.close = () => { @@ -202,14 +201,14 @@ describe('session', () => { session.close().then(() => { expect(closeCalledTimes).toEqual(1) done() - }) + }).catch(done) }, 70000) it('should call cancel current result', done => { const session = newSessionWithConnection(newFakeConnection()) const result = session.run('RETURN 1') - const spiedCancel = jest.spyOn(result, '_cancel') + const spiedCancel = jest.spyOn(result, '_cancel') session.close() .finally(() => { @@ -283,7 +282,7 @@ describe('session', () => { describe.each([ ['.executeWrite()', (session: Session) => session.executeWrite.bind(session)], - ['.executeRead()', (session: Session) => session.executeRead.bind(session)], + ['.executeRead()', (session: Session) => session.executeRead.bind(session)] ])('%s', (_, execute) => { it('should call executor with ManagedTransaction', async () => { const connection = mockBeginWithSuccess(newFakeConnection()) @@ -303,8 +302,8 @@ describe('session', () => { it('should proxy run to the begun transaction', async () => { const connection = mockBeginWithSuccess(newFakeConnection()) const session = newSessionWithConnection(connection, false, FETCH_ALL) - // @ts-ignore - const run = jest.spyOn(Transaction.prototype, 'run').mockImplementation(() => Promise.resolve()) + // @ts-expect-error + const run = jest.spyOn(Transaction.prototype, 'run').mockImplementation(async () => await Promise.resolve()) const status = { functionCalled: false } const query = 'RETURN $a' const params = { a: 1 } @@ -320,13 +319,12 @@ describe('session', () => { }) }) -function mockBeginWithSuccess(connection: FakeConnection) { +function mockBeginWithSuccess (connection: FakeConnection): FakeConnection { const protocol = connection.protocol() - // @ts-ignore connection.protocol = () => { return { ...protocol, - beginTransaction: (params: { afterComplete: () => {}} ) => { + beginTransaction: (params: { afterComplete: () => {}}) => { params.afterComplete() } } @@ -334,21 +332,20 @@ function mockBeginWithSuccess(connection: FakeConnection) { return connection } -function newSessionWithConnection( +function newSessionWithConnection ( connection: Connection, beginTx: boolean = true, fetchSize: number = 1000, lastBookmarks: bookmarks.Bookmarks = bookmarks.Bookmarks.empty() ): Session { - const connectionProvider = new ConnectionProvider() - connectionProvider.acquireConnection = () => Promise.resolve(connection) - connectionProvider.close = () => Promise.resolve() + connectionProvider.acquireConnection = async () => await Promise.resolve(connection) + connectionProvider.close = async () => await Promise.resolve() const session = new Session({ mode: ACCESS_MODE_READ, connectionProvider, - database: "", + database: '', fetchSize, config: {}, reactive: false, @@ -356,11 +353,11 @@ function newSessionWithConnection( }) if (beginTx) { - session.beginTransaction() // force session to acquire new connection + session.beginTransaction().catch(e => {}) // force session to acquire new connection } return session } -function newFakeConnection(): FakeConnection { +function newFakeConnection (): FakeConnection { return new FakeConnection() } diff --git a/packages/core/test/temporal-types.test.ts b/packages/core/test/temporal-types.test.ts index 47439d102..482fbdc5f 100644 --- a/packages/core/test/temporal-types.test.ts +++ b/packages/core/test/temporal-types.test.ts @@ -80,12 +80,11 @@ describe('DateTime', () => { const standardDate = datetime.toStandardDate() - expect(standardDate.getFullYear()).toEqual(datetime.year) expect(standardDate.getMonth()).toEqual(datetime.month - 1) expect(standardDate.getDate()).toEqual(datetime.day) const offsetInMinutes = offset(standardDate) - const offsetAdjust = offsetInMinutes - datetime.timeZoneOffsetSeconds!! / 60 + const offsetAdjust = offsetInMinutes - (datetime.timeZoneOffsetSeconds ?? 0) / 60 const hourDiff = Math.abs(offsetAdjust / 60) const minuteDiff = Math.abs(offsetAdjust % 60) expect(standardDate.getHours()).toBe(datetime.hour - hourDiff) @@ -99,7 +98,6 @@ describe('DateTime', () => { expect(() => datetime.toStandardDate()) .toThrow(new Error('Requires DateTime created with time zone offset')) - }) it('should be the reverse operation of fromStandardDate', () => { @@ -121,6 +119,6 @@ describe('DateTime', () => { * this way using the most common meaning. * The time to add to UTC to get the local time. */ -function offset(date: StandardDate): number { +function offset (date: StandardDate): number { return date.getTimezoneOffset() * -1 } diff --git a/packages/core/test/transaction.test.ts b/packages/core/test/transaction.test.ts index c47aa7a27..9e61a5a3d 100644 --- a/packages/core/test/transaction.test.ts +++ b/packages/core/test/transaction.test.ts @@ -17,35 +17,34 @@ * limitations under the License. */ -import { ConnectionProvider, newError, Transaction, TransactionPromise } from "../src"; -import { Bookmarks } from "../src/internal/bookmarks"; -import { ConnectionHolder } from "../src/internal/connection-holder"; -import { TxConfig } from "../src/internal/tx-config"; -import FakeConnection from "./utils/connection.fake"; - +import { ConnectionProvider, newError, Transaction, TransactionPromise } from '../src' +import { Bookmarks } from '../src/internal/bookmarks' +import { ConnectionHolder } from '../src/internal/connection-holder' +import { TxConfig } from '../src/internal/tx-config' +import FakeConnection from './utils/connection.fake' testTx('Transaction', newRegularTransaction) testTx('TransactionPromise', newTransactionPromise, () => { describe('Promise', () => { - const syncContext = (fn: () => void) => fn() - const asyncContext = (fn: () => void) => setImmediate(fn) + const syncContext = (fn: () => void): void => fn() + const asyncContext = (fn: () => void): NodeJS.Immediate => setImmediate(fn) whenBeginSucceed('async', asyncContext) whenBeginSucceed('sync', syncContext) - function whenBeginSucceed(ctxName: string, ctx: (_: () => void) => void) { + function whenBeginSucceed (ctxName: string, ctx: (_: () => void) => void): void { describe(`when begin processed with success [${ctxName}]`, () => { it('should result resolve with Transaction', async () => { const [tx] = setupTx() - const resolveTx: Transaction = await tx; + const resolveTx: Transaction = await tx - // @ts-ignore + // @ts-expect-error expect(resolveTx.then).toBeUndefined() - // @ts-ignore + // @ts-expect-error expect(resolveTx.catch).toBeUndefined() - // @ts-ignore + // @ts-expect-error expect(resolveTx.finally).toBeUndefined() expect(resolveTx.commit).toBeDefined() @@ -58,7 +57,7 @@ testTx('TransactionPromise', newTransactionPromise, () => { it('should resolve an open Transaction', async () => { const [tx] = setupTx() - const resolved = await tx; + const resolved = await tx expect(resolved.isOpen()).toBe(true) }) @@ -68,7 +67,7 @@ testTx('TransactionPromise', newTransactionPromise, () => { const resolvedTx = await tx - await resolvedTx.run('RETURN 1'); + await resolvedTx.run('RETURN 1') }) it('should be able to commit the resolved transaction', async () => { @@ -76,7 +75,7 @@ testTx('TransactionPromise', newTransactionPromise, () => { const resolvedTx = await tx - await resolvedTx.commit(); + await resolvedTx.commit() }) it('should be able to rollback the resolved transaction', async () => { @@ -84,7 +83,7 @@ testTx('TransactionPromise', newTransactionPromise, () => { const resolvedTx = await tx - await resolvedTx.rollback(); + await resolvedTx.rollback() }) it('should be able to close the resolved transaction', async () => { @@ -92,13 +91,13 @@ testTx('TransactionPromise', newTransactionPromise, () => { const resolvedTx = await tx - await resolvedTx.close(); + await resolvedTx.close() }) it('should the original tx be open', async () => { const [tx] = setupTx() - await tx; + await tx expect(tx.isOpen()).toBe(true) }) @@ -108,7 +107,7 @@ testTx('TransactionPromise', newTransactionPromise, () => { await tx - await tx.run('RETURN 1'); + await tx.run('RETURN 1') }) it('should be able to commit the original transaction', async () => { @@ -116,7 +115,7 @@ testTx('TransactionPromise', newTransactionPromise, () => { await tx - await tx.commit(); + await tx.commit() }) it('should be able to rollback the original transaction', async () => { @@ -124,7 +123,7 @@ testTx('TransactionPromise', newTransactionPromise, () => { await tx - await tx.rollback(); + await tx.rollback() }) it('should be able to close the original transaction', async () => { @@ -132,14 +131,13 @@ testTx('TransactionPromise', newTransactionPromise, () => { await tx - await tx.close(); + await tx.close() }) - function setupTx(): [TransactionPromise] { + function setupTx (): [TransactionPromise] { const connection = newFakeConnection() const protocol = connection.protocol() - // @ts-ignore connection.protocol = () => { return { ...protocol, @@ -157,21 +155,19 @@ testTx('TransactionPromise', newTransactionPromise, () => { return [tx] } - }) } - whenBeginFails('async', asyncContext) whenBeginFails('sync', syncContext) - function whenBeginFails(ctxName: string, ctx: (fn: () => void) => void) { + function whenBeginFails (ctxName: string, ctx: (fn: () => void) => void): void { describe(`when begin fails [${ctxName}]`, () => { it('should fails to resolve the transaction', async () => { const [tx, expectedError] = setupTx() try { - await tx; + await tx fail('should have thrown') } catch (e) { expect(e).toEqual(expectedError) @@ -182,7 +178,7 @@ testTx('TransactionPromise', newTransactionPromise, () => { const [tx] = setupTx() try { - await tx; + await tx } catch (e) { // thats fine } @@ -194,13 +190,13 @@ testTx('TransactionPromise', newTransactionPromise, () => { const [tx] = setupTx() try { - await tx; + await tx } catch (e) { // thats fine } try { - await tx.run('RETURN 1'); + await tx.run('RETURN 1') fail('shoud not succeed') } catch (e) { expect(e).toEqual(newError( @@ -213,13 +209,13 @@ testTx('TransactionPromise', newTransactionPromise, () => { const [tx] = setupTx() try { - await tx; + await tx } catch (e) { // thats fine } try { - await tx.commit(); + await tx.commit() fail('shoud not succeed') } catch (e) { expect(e).toEqual(newError( @@ -232,32 +228,31 @@ testTx('TransactionPromise', newTransactionPromise, () => { const [tx] = setupTx() try { - await tx; + await tx } catch (e) { // thats fine } - await tx.rollback(); + await tx.rollback() }) it('should be able to close the original transaction', async () => { const [tx] = setupTx() try { - await tx; + await tx } catch (e) { // thats fine } - await tx.close(); + await tx.close() }) - function setupTx(): [TransactionPromise, Error] { + function setupTx (): [TransactionPromise, Error] { const connection = newFakeConnection() const protocol = connection.protocol() const expectedError = newError('begin error') - // @ts-ignore connection.protocol = () => { return { ...protocol, @@ -288,7 +283,7 @@ testTx('TransactionPromise', newTransactionPromise, () => { tx._begin(Bookmarks.empty(), TxConfig.empty()) try { - await tx; + await tx fail('should have thrown') } catch (e) { expect(e).toEqual(expectedError) @@ -308,7 +303,7 @@ testTx('TransactionPromise', newTransactionPromise, () => { tx._begin(Bookmarks.empty(), TxConfig.empty()) try { - await tx; + await tx fail('should have thrown') } catch (e) { expect(e).toEqual(expectedError) @@ -318,9 +313,8 @@ testTx('TransactionPromise', newTransactionPromise, () => { }) }) -function testTx(transactionName: string, newTransaction: TransactionFactory, fn: jest.EmptyFunction = () => { }) { +function testTx (transactionName: string, newTransaction: TransactionFactory, fn: jest.EmptyFunction = () => { }): void { describe(transactionName, () => { - describe('.run()', () => { it('should call run with watermarks', async () => { const connection = newFakeConnection() @@ -349,12 +343,11 @@ function testTx(transactionName: string, newTransaction: lowRecordWatermark: 300 }) - var result = tx.run('RETURN 1') + const result = tx.run('RETURN 1') - // @ts-ignore + // @ts-expect-error expect(result._watermarks).toEqual({ high: 700, low: 300 }) }) - }) describe('.close()', () => { @@ -386,11 +379,11 @@ function testTx(transactionName: string, newTransaction: }) describe('when transaction is closed', () => { - const commit = async (tx: Transaction) => tx.commit() - const rollback = async (tx: Transaction) => tx.rollback() - const error = async (tx: Transaction, conn: FakeConnection) => { + const commit = async (tx: Transaction): Promise => await tx.commit() + const rollback = async (tx: Transaction): Promise => await tx.rollback() + const error = async (tx: Transaction, conn: FakeConnection): Promise => { conn.withRollbackError(new Error('rollback error')) - return tx.rollback().catch(() => { }) + return await tx.rollback().catch(() => { }) } it.each([ @@ -415,37 +408,35 @@ function testTx(transactionName: string, newTransaction: }) } -interface TransactionFactory { - (_: { - connection: FakeConnection - fetchSize?: number - highRecordWatermark?: number, - lowRecordWatermark?: number - }): T -} +type TransactionFactory = (_: { + connection: FakeConnection + fetchSize?: number + highRecordWatermark?: number + lowRecordWatermark?: number +}) => T -function newTransactionPromise({ +function newTransactionPromise ({ connection, fetchSize = 1000, highRecordWatermark = 700, lowRecordWatermark = 300, errorResolvingConnection = undefined }: { - connection: FakeConnection | void + connection?: FakeConnection fetchSize?: number - highRecordWatermark?: number, + highRecordWatermark?: number lowRecordWatermark?: number errorResolvingConnection?: Error }): TransactionPromise { const connectionProvider = new ConnectionProvider() - // @ts-ignore - connectionProvider.acquireConnection = () => { - if (errorResolvingConnection) { - return Promise.reject(errorResolvingConnection) + // @ts-expect-error + connectionProvider.acquireConnection = async () => { + if (errorResolvingConnection != null) { + return await Promise.reject(errorResolvingConnection) } - return Promise.resolve(connection) + return await Promise.resolve(connection) } - connectionProvider.close = () => Promise.resolve() + connectionProvider.close = async () => await Promise.resolve() const connectionHolder = new ConnectionHolder({ connectionProvider }) connectionHolder.initializeConnection() @@ -457,7 +448,7 @@ function newTransactionPromise({ onConnection: () => { }, reactive: false, fetchSize, - impersonatedUser: "", + impersonatedUser: '', highRecordWatermark, lowRecordWatermark }) @@ -465,7 +456,7 @@ function newTransactionPromise({ return transaction } -function newRegularTransaction({ +function newRegularTransaction ({ connection, fetchSize = 1000, highRecordWatermark = 700, @@ -473,12 +464,12 @@ function newRegularTransaction({ }: { connection: FakeConnection fetchSize?: number - highRecordWatermark?: number, + highRecordWatermark?: number lowRecordWatermark?: number }): Transaction { const connectionProvider = new ConnectionProvider() - connectionProvider.acquireConnection = () => Promise.resolve(connection) - connectionProvider.close = () => Promise.resolve() + connectionProvider.acquireConnection = async () => await Promise.resolve(connection) + connectionProvider.close = async () => await Promise.resolve() const connectionHolder = new ConnectionHolder({ connectionProvider }) connectionHolder.initializeConnection() @@ -490,7 +481,7 @@ function newRegularTransaction({ onConnection: () => { }, reactive: false, fetchSize, - impersonatedUser: "", + impersonatedUser: '', highRecordWatermark, lowRecordWatermark }) @@ -498,6 +489,6 @@ function newRegularTransaction({ return transaction } -function newFakeConnection(): FakeConnection { +function newFakeConnection (): FakeConnection { return new FakeConnection() } diff --git a/packages/core/test/utils/connection.fake.ts b/packages/core/test/utils/connection.fake.ts index aaae1e024..fce1c493c 100644 --- a/packages/core/test/utils/connection.fake.ts +++ b/packages/core/test/utils/connection.fake.ts @@ -17,10 +17,9 @@ * limitations under the License. */ -import { Connection, ResultObserver, Record, ResultSummary } from '../../src' +import { Connection, ResultObserver, ResultSummary } from '../../src' import { ResultStreamObserver } from '../../src/internal/observers' - /** * This class is like a mock of {@link Connection} that tracks invocations count. * It tries to maintain same "interface" as {@link Connection}. @@ -30,7 +29,7 @@ import { ResultStreamObserver } from '../../src/internal/observers' */ export default class FakeConnection extends Connection { private _open: boolean - private _id: number + private readonly _id: number private _databaseId: string | null private _requestRoutingInformationMock: ((params: any) => void) | null public creationTimestamp: number @@ -47,7 +46,7 @@ export default class FakeConnection extends Connection { public rollbackInvoked: number public _rollbackError: Error | null - constructor() { + constructor () { super() this._open = true @@ -70,31 +69,32 @@ export default class FakeConnection extends Connection { this._rollbackError = null } - get id(): string { + get id (): string { return this._id.toString() } - get databaseId(): string { - return this._databaseId!! + get databaseId (): string { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return this._databaseId! } - set databaseId(value) { + set databaseId (value: string) { this._databaseId = value } - get server() { + get server (): any { return this._server } - get version() { + get version (): string { return this._server.version } - set version(value) { + set version (value: string) { this._server.version = value } - protocol() { + protocol (): any { // return fake protocol object that simply records seen queries and parameters return { run: (query: string, parameters: any | undefined, protocolOptions: any | undefined): ResultStreamObserver => { @@ -106,11 +106,11 @@ export default class FakeConnection extends Connection { commitTransaction: () => { return mockResultStreamObserver('COMMIT', {}) }, - beginTransaction: () => { - return Promise.resolve() + beginTransaction: async () => { + return await Promise.resolve() }, rollbackTransaction: () => { - this.rollbackInvoked ++ + this.rollbackInvoked++ if (this._rollbackError !== null) { return mockResultStreamObserverWithError('ROLLBACK', {}, this._rollbackError) } @@ -118,7 +118,7 @@ export default class FakeConnection extends Connection { }, requestRoutingInformation: (params: any | undefined) => { this.seenRequestRoutingInformation.push(params) - if (this._requestRoutingInformationMock) { + if (this._requestRoutingInformationMock != null) { this._requestRoutingInformationMock(params) } }, @@ -126,76 +126,74 @@ export default class FakeConnection extends Connection { } } - resetAndFlush() { + async resetAndFlush (): Promise { this.resetInvoked++ - return Promise.resolve() } - _release() { + async _release (): Promise { this.releaseInvoked++ - return Promise.resolve() } - isOpen() { + isOpen (): boolean { return this._open } - isNeverReleased() { + isNeverReleased (): boolean { return this.isReleasedTimes(0) } - isReleasedOnce() { + isReleasedOnce (): boolean { return this.isReleasedTimes(1) } - isReleasedTimes(times: number) { + isReleasedTimes (times: number): boolean { return this.resetInvoked === times && this.releaseInvoked === times } - _handleProtocolError(message: string) { + _handleProtocolError (message: string): void { this.protocolErrorsHandled++ this.seenProtocolErrors.push(message) } - withProtocolVersion(version: number) { + withProtocolVersion (version: number): FakeConnection { this.protocolVersion = version return this } - withCreationTimestamp(value: number) { + withCreationTimestamp (value: number): FakeConnection { this.creationTimestamp = value return this } - withRequestRoutingInformationMock(requestRoutingInformationMock: (params: any) => void) { + withRequestRoutingInformationMock (requestRoutingInformationMock: (params: any) => void): FakeConnection { this._requestRoutingInformationMock = requestRoutingInformationMock return this } - withRollbackError(error: Error) { + withRollbackError (error: Error): FakeConnection { this._rollbackError = error return this } - closed() { + closed (): FakeConnection { this._open = false return this } } -function mockResultStreamObserverWithError (query: string, parameters: any | undefined, error: Error) { +function mockResultStreamObserverWithError (query: string, parameters: any | undefined, error: Error): ResultStreamObserver { const observer = mockResultStreamObserver(query, parameters) observer.subscribe = (observer: ResultObserver) => { - if (observer && observer.onError) { + if (observer?.onError != null) { observer.onError(error) } } return observer } -function mockResultStreamObserver(query: string, parameters: any | undefined): ResultStreamObserver { +function mockResultStreamObserver (query: string, parameters: any | undefined): ResultStreamObserver { return { - onError: (error: any) => { }, + onError: (e: any) => { }, onCompleted: () => { }, onNext: (result: any) => { }, cancel: () => { }, @@ -204,10 +202,9 @@ function mockResultStreamObserver(query: string, parameters: any | undefined): R resume: () => { }, markCompleted: () => { }, subscribe: (observer: ResultObserver) => { - if (observer && observer.onCompleted) { + if (observer?.onCompleted != null) { observer.onCompleted(new ResultSummary(query, parameters, {})) } - } } } From 4807e1b6678914ae298d96f34db202709b3f02ca Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Wed, 20 Apr 2022 10:52:06 +0200 Subject: [PATCH 04/13] Applying linter to packages/bolt-connection/src --- .../src/bolt/bolt-protocol-util.js | 3 +- .../src/bolt/bolt-protocol-v1.js | 3 ++ .../src/bolt/bolt-protocol-v3.js | 1 + .../src/bolt/bolt-protocol-v4x0.js | 1 + .../src/bolt/bolt-protocol-v4x4.js | 5 ++-- .../src/bolt/bolt-protocol-v5x0.js | 4 +-- packages/bolt-connection/src/bolt/create.js | 1 + .../src/bolt/request-message.js | 6 ++-- .../src/bolt/response-handler.js | 1 - .../src/bolt/routing-table-raw.js | 1 + .../src/bolt/stream-observers.js | 18 ++++++++---- .../src/channel/browser/browser-channel.js | 8 ++++-- .../src/channel/channel-buf.js | 3 +- .../src/channel/channel-config.js | 1 - .../bolt-connection/src/channel/node/index.js | 1 - .../src/channel/node/node-channel.js | 2 +- .../connection-provider-direct.js | 2 +- .../connection-provider-routing.js | 28 +++++++++---------- .../src/connection/connection-channel.js | 2 +- .../connection/connection-error-handler.js | 4 +-- .../src/connection/connection.js | 2 +- .../src/packstream/packstream-v1.js | 8 +++--- .../src/packstream/packstream-v2.js | 2 +- .../src/packstream/packstream-v5.js | 9 +++--- packages/bolt-connection/src/pool/pool.js | 14 +++++----- .../src/rediscovery/rediscovery.js | 3 +- packages/bolt-connection/types/index.d.ts | 8 +++--- 27 files changed, 76 insertions(+), 65 deletions(-) diff --git a/packages/bolt-connection/src/bolt/bolt-protocol-util.js b/packages/bolt-connection/src/bolt/bolt-protocol-util.js index 311eacc03..8a6ef2e4d 100644 --- a/packages/bolt-connection/src/bolt/bolt-protocol-util.js +++ b/packages/bolt-connection/src/bolt/bolt-protocol-util.js @@ -17,6 +17,7 @@ * limitations under the License. */ import { newError } from 'neo4j-driver-core' +// eslint-disable-next-line no-unused-vars import { ResultStreamObserver } from './stream-observers' /** @@ -59,7 +60,7 @@ function assertDatabaseIsEmpty (database, onProtocolError = () => {}, observer) /** * Asserts that the passed-in impersonated user is empty - * @param {string} impersonatedUser + * @param {string} impersonatedUser * @param {function (err:Error)} onProtocolError Called when it does have impersonated user set * @param {any} observer */ diff --git a/packages/bolt-connection/src/bolt/bolt-protocol-v1.js b/packages/bolt-connection/src/bolt/bolt-protocol-v1.js index 46e350635..a2648443e 100644 --- a/packages/bolt-connection/src/bolt/bolt-protocol-v1.js +++ b/packages/bolt-connection/src/bolt/bolt-protocol-v1.js @@ -21,6 +21,7 @@ import { assertTxConfigIsEmpty, assertImpersonatedUserIsEmpty } from './bolt-protocol-util' +// eslint-disable-next-line no-unused-vars import { Chunker } from '../channel' import { v1 } from '../packstream' import RequestMessage from './request-message' @@ -28,6 +29,7 @@ import { LoginObserver, ResetObserver, ResultStreamObserver, + // eslint-disable-next-line no-unused-vars StreamObserver } from './stream-observers' import { internal } from 'neo4j-driver-core' @@ -35,6 +37,7 @@ import { internal } from 'neo4j-driver-core' const { bookmarks: { Bookmarks }, constants: { ACCESS_MODE_WRITE, BOLT_PROTOCOL_V1 }, + // eslint-disable-next-line no-unused-vars logger: { Logger }, txConfig: { TxConfig } } = internal diff --git a/packages/bolt-connection/src/bolt/bolt-protocol-v3.js b/packages/bolt-connection/src/bolt/bolt-protocol-v3.js index 8e59cf24e..a4fbe3d66 100644 --- a/packages/bolt-connection/src/bolt/bolt-protocol-v3.js +++ b/packages/bolt-connection/src/bolt/bolt-protocol-v3.js @@ -28,6 +28,7 @@ import { import { internal } from 'neo4j-driver-core' const { + // eslint-disable-next-line no-unused-vars bookmarks: { Bookmarks }, constants: { BOLT_PROTOCOL_V3 }, txConfig: { TxConfig } diff --git a/packages/bolt-connection/src/bolt/bolt-protocol-v4x0.js b/packages/bolt-connection/src/bolt/bolt-protocol-v4x0.js index fd7f36487..834faf415 100644 --- a/packages/bolt-connection/src/bolt/bolt-protocol-v4x0.js +++ b/packages/bolt-connection/src/bolt/bolt-protocol-v4x0.js @@ -27,6 +27,7 @@ import { import { internal } from 'neo4j-driver-core' const { + // eslint-disable-next-line no-unused-vars bookmarks: { Bookmarks }, constants: { BOLT_PROTOCOL_V4_0, FETCH_ALL }, txConfig: { TxConfig } diff --git a/packages/bolt-connection/src/bolt/bolt-protocol-v4x4.js b/packages/bolt-connection/src/bolt/bolt-protocol-v4x4.js index 7611a0fff..634edbf82 100644 --- a/packages/bolt-connection/src/bolt/bolt-protocol-v4x4.js +++ b/packages/bolt-connection/src/bolt/bolt-protocol-v4x4.js @@ -24,11 +24,11 @@ import { RouteObserver, ResultStreamObserver } from './stream-observers' const { constants: { BOLT_PROTOCOL_V4_4, FETCH_ALL }, - bookmarks: { Bookmarks }, + bookmarks: { Bookmarks } } = internal export default class BoltProtocol extends BoltProtocolV43 { - get version() { + get version () { return BOLT_PROTOCOL_V4_4 } @@ -153,5 +153,4 @@ export default class BoltProtocol extends BoltProtocolV43 { return observer } - } diff --git a/packages/bolt-connection/src/bolt/bolt-protocol-v5x0.js b/packages/bolt-connection/src/bolt/bolt-protocol-v5x0.js index 1e21960bc..c4e3e4d93 100644 --- a/packages/bolt-connection/src/bolt/bolt-protocol-v5x0.js +++ b/packages/bolt-connection/src/bolt/bolt-protocol-v5x0.js @@ -22,11 +22,11 @@ import { v5 } from '../packstream' import { internal } from 'neo4j-driver-core' const { - constants: { BOLT_PROTOCOL_V5_0 }, + constants: { BOLT_PROTOCOL_V5_0 } } = internal export default class BoltProtocol extends BoltProtocolV44 { - get version() { + get version () { return BOLT_PROTOCOL_V5_0 } diff --git a/packages/bolt-connection/src/bolt/create.js b/packages/bolt-connection/src/bolt/create.js index 3a641fede..c1e53d006 100644 --- a/packages/bolt-connection/src/bolt/create.js +++ b/packages/bolt-connection/src/bolt/create.js @@ -27,6 +27,7 @@ import BoltProtocolV4x2 from './bolt-protocol-v4x2' import BoltProtocolV4x3 from './bolt-protocol-v4x3' import BoltProtocolV4x4 from './bolt-protocol-v4x4' import BoltProtocolV5x0 from './bolt-protocol-v5x0' +// eslint-disable-next-line no-unused-vars import { Chunker, Dechunker } from '../channel' import ResponseHandler from './response-handler' diff --git a/packages/bolt-connection/src/bolt/request-message.js b/packages/bolt-connection/src/bolt/request-message.js index a5505da9d..5183b3cae 100644 --- a/packages/bolt-connection/src/bolt/request-message.js +++ b/packages/bolt-connection/src/bolt/request-message.js @@ -250,14 +250,14 @@ export default class RequestMessage { * @param {string} databaseContext.impersonatedUser The name of the user to impersonation when getting the routing table. * @return {RequestMessage} the ROUTE message. */ - static routeV4x4 (routingContext = {}, bookmarks = [], databaseContext = {}) { + static routeV4x4 (routingContext = {}, bookmarks = [], databaseContext = {}) { const dbContext = {} - if ( databaseContext.databaseName ) { + if (databaseContext.databaseName) { dbContext.db = databaseContext.databaseName } - if ( databaseContext.impersonatedUser ) { + if (databaseContext.impersonatedUser) { dbContext.imp_user = databaseContext.impersonatedUser } diff --git a/packages/bolt-connection/src/bolt/response-handler.js b/packages/bolt-connection/src/bolt/response-handler.js index 38b611874..25fa2dd58 100644 --- a/packages/bolt-connection/src/bolt/response-handler.js +++ b/packages/bolt-connection/src/bolt/response-handler.js @@ -193,5 +193,4 @@ export default class ResponseHandler { _resetFailure () { this._currentFailure = null } - } diff --git a/packages/bolt-connection/src/bolt/routing-table-raw.js b/packages/bolt-connection/src/bolt/routing-table-raw.js index d8d50ae80..28d3530e9 100644 --- a/packages/bolt-connection/src/bolt/routing-table-raw.js +++ b/packages/bolt-connection/src/bolt/routing-table-raw.js @@ -16,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +// eslint-disable-next-line no-unused-vars import Record from 'neo4j-driver-core' /** diff --git a/packages/bolt-connection/src/bolt/stream-observers.js b/packages/bolt-connection/src/bolt/stream-observers.js index 0016f3e9b..4ad0ce445 100644 --- a/packages/bolt-connection/src/bolt/stream-observers.js +++ b/packages/bolt-connection/src/bolt/stream-observers.js @@ -16,17 +16,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { newError, error, Integer, Record, json, internal } from 'neo4j-driver-core' +import { + newError, + error, + // eslint-disable-next-line no-unused-vars + Integer, + Record, + json, + internal +} from 'neo4j-driver-core' import RawRoutingTable from './routing-table-raw' const { - constants: { FETCH_ALL }, + constants: { FETCH_ALL } } = internal const { PROTOCOL_ERROR } = error class StreamObserver { onNext (rawRecord) {} - onError (error) {} + onError (_error) {} onCompleted (meta) {} } @@ -100,7 +108,7 @@ class ResultStreamObserver extends StreamObserver { this._highRecordWatermark = highRecordWatermark this._setState(reactive ? _states.READY : _states.READY_STREAMING) this._setupAutoPull() - this._paused = false; + this._paused = false } /** @@ -643,7 +651,7 @@ const _states = { pull: () => {} }, FAILED: { - onError: error => { + onError: _error => { // more errors are ignored }, name: () => { diff --git a/packages/bolt-connection/src/channel/browser/browser-channel.js b/packages/bolt-connection/src/channel/browser/browser-channel.js index 9476c0325..7bdcadc9b 100644 --- a/packages/bolt-connection/src/channel/browser/browser-channel.js +++ b/packages/bolt-connection/src/channel/browser/browser-channel.js @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +/* eslint-env browser */ import ChannelBuffer from '../channel-buf' import { newError, internal } from 'neo4j-driver-core' @@ -26,8 +26,10 @@ const { // Just to be sure that these values are with us even after WebSocket is injected // for tests. +// eslint-disable-next-line no-unused-vars const WS_CONNECTING = 0 const WS_OPEN = 1 +// eslint-disable-next-line no-unused-vars const WS_CLOSING = 2 const WS_CLOSED = 3 @@ -184,7 +186,7 @@ export default class WebSocketChannel { /** * Stops the receive timeout for the channel. */ - stopReceiveTimeout() { + stopReceiveTimeout () { } /** @@ -265,7 +267,7 @@ function isIPv6Address (hostAndPort) { function asWindowsFriendlyIPv6Address (scheme, address) { // replace all ':' with '-' - const hostWithoutColons = address.host().replace(new RegExp(':', 'g'), '-') + const hostWithoutColons = address.host().replace(/:/g, '-') // replace '%' with 's' for link-local IPv6 address like 'fe80::1%lo0' const hostWithoutPercent = hostWithoutColons.replace('%', 's') diff --git a/packages/bolt-connection/src/channel/channel-buf.js b/packages/bolt-connection/src/channel/channel-buf.js index fad2adfb7..73e3700cc 100644 --- a/packages/bolt-connection/src/channel/channel-buf.js +++ b/packages/bolt-connection/src/channel/channel-buf.js @@ -76,7 +76,7 @@ export default class ChannelBuffer extends BaseBuffer { /** * Allocate a buffer - * + * * @param {number} size The buffer sizzer * @returns {BaseBuffer} The buffer */ @@ -84,7 +84,6 @@ export function alloc (size) { return new ChannelBuffer(size) } - function newChannelJSBuffer (arg) { if (arg instanceof buffer.Buffer) { return arg diff --git a/packages/bolt-connection/src/channel/channel-config.js b/packages/bolt-connection/src/channel/channel-config.js index 85df9b22c..507167b81 100644 --- a/packages/bolt-connection/src/channel/channel-config.js +++ b/packages/bolt-connection/src/channel/channel-config.js @@ -87,4 +87,3 @@ function extractTrustedCertificates (driverConfig) { function extractKnownHostsPath (driverConfig) { return driverConfig.knownHosts || null } - diff --git a/packages/bolt-connection/src/channel/node/index.js b/packages/bolt-connection/src/channel/node/index.js index a9c7bbc91..dca87205a 100644 --- a/packages/bolt-connection/src/channel/node/index.js +++ b/packages/bolt-connection/src/channel/node/index.js @@ -33,4 +33,3 @@ NOTE: exports in this module should have exactly the same names/structure as exp export const Channel = NodeChannel export const HostNameResolver = NodeHostNameResolver - diff --git a/packages/bolt-connection/src/channel/node/node-channel.js b/packages/bolt-connection/src/channel/node/node-channel.js index 75d5d2ed6..a4cca7fa1 100644 --- a/packages/bolt-connection/src/channel/node/node-channel.js +++ b/packages/bolt-connection/src/channel/node/node-channel.js @@ -361,7 +361,7 @@ export default class NodeChannel { /** * Stops the receive timeout for the channel. */ - stopReceiveTimeout() { + stopReceiveTimeout () { if (this._receiveTimeout !== null && this._receiveTimeoutStarted) { this._receiveTimeoutStarted = false this._conn.setTimeout(0) diff --git a/packages/bolt-connection/src/connection-provider/connection-provider-direct.js b/packages/bolt-connection/src/connection-provider/connection-provider-direct.js index 96a4c7295..d93b0638b 100644 --- a/packages/bolt-connection/src/connection-provider/connection-provider-direct.js +++ b/packages/bolt-connection/src/connection-provider/connection-provider-direct.js @@ -29,7 +29,7 @@ const { constants: { BOLT_PROTOCOL_V3, BOLT_PROTOCOL_V4_0, BOLT_PROTOCOL_V4_4 } } = internal -const { SERVICE_UNAVAILABLE, newError } = error +const { SERVICE_UNAVAILABLE } = error export default class DirectConnectionProvider extends PooledConnectionProvider { constructor ({ id, config, log, address, userAgent, authToken }) { diff --git a/packages/bolt-connection/src/connection-provider/connection-provider-routing.js b/packages/bolt-connection/src/connection-provider/connection-provider-routing.js index 8bb28688f..d8f573a0a 100644 --- a/packages/bolt-connection/src/connection-provider/connection-provider-routing.js +++ b/packages/bolt-connection/src/connection-provider/connection-provider-routing.js @@ -41,13 +41,12 @@ const { } } = internal - const PROCEDURE_NOT_FOUND_CODE = 'Neo.ClientError.Procedure.ProcedureNotFound' const DATABASE_NOT_FOUND_CODE = 'Neo.ClientError.Database.DatabaseNotFound' const INVALID_BOOKMARK_CODE = 'Neo.ClientError.Transaction.InvalidBookmark' -const INVALID_BOOKMARK_MIXTURE_CODE = +const INVALID_BOOKMARK_MIXTURE_CODE = 'Neo.ClientError.Transaction.InvalidBookmarkMixture' -const AUTHORIZATION_EXPIRED_CODE = +const AUTHORIZATION_EXPIRED_CODE = 'Neo.ClientError.Security.AuthorizationExpired' const SYSTEM_DB_NAME = 'system' @@ -257,7 +256,7 @@ export default class RoutingConnectionProvider extends PooledConnectionProvider }) const servers = accessMode === WRITE ? routingTable.writers : routingTable.readers - + let error = newError( `No servers available for database '${context.database}' with access mode '${accessMode}'`, SERVICE_UNAVAILABLE @@ -285,7 +284,7 @@ export default class RoutingConnectionProvider extends PooledConnectionProvider } forgetWriter (address, database) { - this._routingTableRegistry.apply( database, { + this._routingTableRegistry.apply(database, { applyWhenExists: routingTable => routingTable.forgetWriter(address) }) } @@ -510,7 +509,7 @@ export default class RoutingConnectionProvider extends PooledConnectionProvider errorCode: SESSION_EXPIRED, handleAuthorizationExpired: (error, address) => this._handleAuthorizationExpired(error, address) }) - + const connectionProvider = new SingleConnectionProvider( new DelegateConnection(connection, databaseSpecificErrorHandler)) @@ -535,7 +534,7 @@ export default class RoutingConnectionProvider extends PooledConnectionProvider } } - _handleRediscoveryError(error, routerAddress) { + _handleRediscoveryError (error, routerAddress) { if (_isFailFastError(error) || _isFailFastSecurityError(error)) { throw error } else if (error.code === PROCEDURE_NOT_FOUND_CODE) { @@ -578,9 +577,9 @@ export default class RoutingConnectionProvider extends PooledConnectionProvider this._routingTableRegistry.register( newRoutingTable ) - + onDatabaseNameResolved(newRoutingTable.database) - + this._log.info(`Updated routing table ${newRoutingTable}`) } @@ -639,14 +638,14 @@ class RoutingTableRegistry { /** * Retrieves a routing table from a given database name - * + * * @param {string|impersonatedUser} impersonatedUser The impersonated User * @param {string} database The database name * @param {function()|RoutingTable} defaultSupplier The routing table supplier, if it's not a function or not exists, it will return itself as default value * @returns {RoutingTable} The routing table for the respective database */ get (database, defaultSupplier) { - if (this._tables.has(database) ) { + if (this._tables.has(database)) { return this._tables.get(database) } return typeof defaultSupplier === 'function' @@ -690,14 +689,13 @@ function _isFailFastError (error) { return [ DATABASE_NOT_FOUND_CODE, INVALID_BOOKMARK_CODE, - INVALID_BOOKMARK_MIXTURE_CODE, + INVALID_BOOKMARK_MIXTURE_CODE ].includes(error.code) } function _isFailFastSecurityError (error) { - return error.code.startsWith('Neo.ClientError.Security.') && + return error.code.startsWith('Neo.ClientError.Security.') && ![ - AUTHORIZATION_EXPIRED_CODE, + AUTHORIZATION_EXPIRED_CODE ].includes(error.code) } - diff --git a/packages/bolt-connection/src/connection/connection-channel.js b/packages/bolt-connection/src/connection/connection-channel.js index a00b01288..d1325b5e1 100644 --- a/packages/bolt-connection/src/connection/connection-channel.js +++ b/packages/bolt-connection/src/connection/connection-channel.js @@ -355,7 +355,7 @@ export default class ChannelConnection extends Connection { * Starts and stops the receive timeout timer. * @param {number} requestsNumber Ongoing requests number */ - _handleOngoingRequestsNumberChange(requestsNumber) { + _handleOngoingRequestsNumberChange (requestsNumber) { if (requestsNumber === 0) { this._ch.stopReceiveTimeout() } else { diff --git a/packages/bolt-connection/src/connection/connection-error-handler.js b/packages/bolt-connection/src/connection/connection-error-handler.js index bafcc8a82..de844e96f 100644 --- a/packages/bolt-connection/src/connection/connection-error-handler.js +++ b/packages/bolt-connection/src/connection/connection-error-handler.js @@ -77,8 +77,8 @@ export default class ConnectionErrorHandler { } function isAutorizationExpiredError (error) { - return error && ( - error.code === 'Neo.ClientError.Security.AuthorizationExpired' || + return error && ( + error.code === 'Neo.ClientError.Security.AuthorizationExpired' || error.code === 'Neo.ClientError.Security.TokenExpired' ) } diff --git a/packages/bolt-connection/src/connection/connection.js b/packages/bolt-connection/src/connection/connection.js index 0794867db..21cdd3c1a 100644 --- a/packages/bolt-connection/src/connection/connection.js +++ b/packages/bolt-connection/src/connection/connection.js @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +// eslint-disable-next-line no-unused-vars import { ResultStreamObserver, BoltProtocol } from '../bolt' export default class Connection { diff --git a/packages/bolt-connection/src/packstream/packstream-v1.js b/packages/bolt-connection/src/packstream/packstream-v1.js index 5f5893e9d..1b77f096a 100644 --- a/packages/bolt-connection/src/packstream/packstream-v1.js +++ b/packages/bolt-connection/src/packstream/packstream-v1.js @@ -155,8 +155,8 @@ class Packer { `It is not allowed to pass paths in query parameters, given: ${x}` ) } else if (x instanceof Structure) { - var packableFields = [] - for (var i = 0; i < x.fields.length; i++) { + const packableFields = [] + for (let i = 0; i < x.fields.length; i++) { packableFields[i] = this.packable(x.fields[i]) } return () => this.packStruct(x.signature, packableFields) @@ -208,8 +208,8 @@ class Packer { } packInteger (x) { - var high = x.high - var low = x.low + const high = x.high + const low = x.low if (x.greaterThanOrEqual(-0x10) && x.lessThan(0x80)) { this._ch.writeInt8(low) diff --git a/packages/bolt-connection/src/packstream/packstream-v2.js b/packages/bolt-connection/src/packstream/packstream-v2.js index d1c1b8ed2..7a1f49607 100644 --- a/packages/bolt-connection/src/packstream/packstream-v2.js +++ b/packages/bolt-connection/src/packstream/packstream-v2.js @@ -626,7 +626,7 @@ function convertIntegerPropsIfNeeded (obj, disableLosslessIntegers, useBigInt) { const clone = Object.create(Object.getPrototypeOf(obj)) for (const prop in obj) { - if (obj.hasOwnProperty(prop)) { + if (Object.prototype.hasOwnProperty.call(obj, prop) === true) { const value = obj[prop] clone[prop] = isInt(value) ? convert(value) : value } diff --git a/packages/bolt-connection/src/packstream/packstream-v5.js b/packages/bolt-connection/src/packstream/packstream-v5.js index 0d8886d20..e99731336 100644 --- a/packages/bolt-connection/src/packstream/packstream-v5.js +++ b/packages/bolt-connection/src/packstream/packstream-v5.js @@ -39,13 +39,12 @@ export class Unpacker extends v2.Unpacker { * @param {boolean} disableLosslessIntegers if this unpacker should convert all received integers to native JS numbers. * @param {boolean} useBigInt if this unpacker should convert all received integers to Bigint */ - constructor (disableLosslessIntegers = false, useBigInt = false) { - this._disableLosslessIntegers = disableLosslessIntegers - this._useBigInt = useBigInt + constructor (disableLosslessIntegers = false, useBigInt = false) { + super(disableLosslessIntegers, useBigInt) this._defaultIdentity = this._getDefaultIdentity() } - _getDefaultIdentity() { + _getDefaultIdentity () { if (this._useBigInt) { return BigInt(-1) } else if (this._disableLosslessIntegers) { @@ -97,6 +96,6 @@ export class Unpacker extends v2.Unpacker { } } -function _valueOrDefault(value, defaultValue) { +function _valueOrDefault (value, defaultValue) { return value === null ? defaultValue : value } diff --git a/packages/bolt-connection/src/pool/pool.js b/packages/bolt-connection/src/pool/pool.js index b5d01bdb7..dca648bc1 100644 --- a/packages/bolt-connection/src/pool/pool.js +++ b/packages/bolt-connection/src/pool/pool.js @@ -83,7 +83,7 @@ class Pool { allRequests[key] = [] } return new Promise((resolve, reject) => { - let request + let request = null const timeoutId = setTimeout(() => { // acquisition timeout fired @@ -416,16 +416,16 @@ class PendingRequest { } class PoolState { - constructor() { - this._active = true; + constructor () { + this._active = true } - isActive() { - return this._active; + isActive () { + return this._active } - close() { - this._active = false; + close () { + this._active = false } } diff --git a/packages/bolt-connection/src/rediscovery/rediscovery.js b/packages/bolt-connection/src/rediscovery/rediscovery.js index e8cbeb36d..2178a3557 100644 --- a/packages/bolt-connection/src/rediscovery/rediscovery.js +++ b/packages/bolt-connection/src/rediscovery/rediscovery.js @@ -17,6 +17,7 @@ * limitations under the License. */ import RoutingTable from './routing-table' +// eslint-disable-next-line no-unused-vars import { Session } from 'neo4j-driver-core' export default class Rediscovery { @@ -70,7 +71,7 @@ export default class Rediscovery { afterComplete: session._onComplete }, onCompleted: resolve, - onError: reject, + onError: reject }) }) } diff --git a/packages/bolt-connection/types/index.d.ts b/packages/bolt-connection/types/index.d.ts index cb696f9c2..a1dae4d79 100644 --- a/packages/bolt-connection/types/index.d.ts +++ b/packages/bolt-connection/types/index.d.ts @@ -16,19 +16,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { +import { ConnectionProvider } from 'neo4j-driver-core' declare class DirectConnectionProvider extends ConnectionProvider { - constructor(config: any) + constructor (config: any) } declare class RoutingConnectionProvider extends ConnectionProvider { - constructor(config: any) + constructor (config: any) } export { DirectConnectionProvider, RoutingConnectionProvider -} \ No newline at end of file +} From b6343b7c5e8d8cfd12d05442e23882e5931a54d8 Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Wed, 20 Apr 2022 11:23:24 +0200 Subject: [PATCH 05/13] Applying linter to packages/bolt-connection/test --- .../test/bolt/bolt-protocol-v1.test.js | 6 +- .../test/bolt/bolt-protocol-v2.test.js | 6 +- .../test/bolt/bolt-protocol-v3.test.js | 6 +- .../test/bolt/bolt-protocol-v4x0.test.js | 8 +- .../test/bolt/bolt-protocol-v4x1.test.js | 6 +- .../test/bolt/bolt-protocol-v4x2.test.js | 6 +- .../test/bolt/bolt-protocol-v4x3.test.js | 6 +- .../test/bolt/bolt-protocol-v4x4.test.js | 4 +- .../test/bolt/bolt-protocol-v5x0.test.js | 4 +- .../test/bolt/request-message.test.js | 4 +- .../test/bolt/routing-table-raw.test.js | 1 - .../test/bolt/stream-observer.test.js | 8 +- .../channel/browser/browser-channel.test.js | 1 + .../test/channel/encode-decode.test.js | 7 +- .../test/channel/node/node-channel.test.js | 18 ++-- .../connection-provider-direct.test.js | 18 ++-- .../connection-provider-routing.test.js | 88 +++++++-------- .../connection/connection-channel.test.js | 12 +-- .../connection-error-handler.test.js | 1 - .../test/packstream/packstream-v5.test.js | 101 +++++++++--------- .../bolt-connection/test/pool/pool.test.js | 22 ++-- .../test/rediscovery/rediscovery.test.js | 3 +- 22 files changed, 159 insertions(+), 177 deletions(-) diff --git a/packages/bolt-connection/test/bolt/bolt-protocol-v1.test.js b/packages/bolt-connection/test/bolt/bolt-protocol-v1.test.js index 9686c7812..b11757ed7 100644 --- a/packages/bolt-connection/test/bolt/bolt-protocol-v1.test.js +++ b/packages/bolt-connection/test/bolt/bolt-protocol-v1.test.js @@ -280,7 +280,7 @@ describe('#unit BoltProtocolV1', () => { describe('Bolt v4.4', () => { /** * @param {string} impersonatedUser The impersonated user. - * @param {function(protocol: BoltProtocolV1)} fn + * @param {function(protocol: BoltProtocolV1)} fn */ function verifyImpersonationNotSupportedErrror (impersonatedUser, fn) { const recorder = new utils.MessageRecordingConnection() @@ -294,7 +294,7 @@ describe('#unit BoltProtocolV1', () => { } describe('beginTransaction', () => { - function verifyBeginTransaction(impersonatedUser) { + function verifyBeginTransaction (impersonatedUser) { verifyImpersonationNotSupportedErrror( impersonatedUser, protocol => protocol.beginTransaction({ impersonatedUser })) @@ -353,7 +353,7 @@ describe('#unit BoltProtocolV1', () => { txConfig: TxConfig.empty(), mode: WRITE, lowRecordWatermark: 100, - highRecordWatermark: 200, + highRecordWatermark: 200 }) expect(observer._lowRecordWatermark).toEqual(100) diff --git a/packages/bolt-connection/test/bolt/bolt-protocol-v2.test.js b/packages/bolt-connection/test/bolt/bolt-protocol-v2.test.js index d62878445..99eb55a28 100644 --- a/packages/bolt-connection/test/bolt/bolt-protocol-v2.test.js +++ b/packages/bolt-connection/test/bolt/bolt-protocol-v2.test.js @@ -55,7 +55,7 @@ describe('#unit BoltProtocolV2', () => { describe('Bolt v4.4', () => { /** * @param {string} impersonatedUser The impersonated user. - * @param {function(protocol: BoltProtocolV2)} fn + * @param {function(protocol: BoltProtocolV2)} fn */ function verifyImpersonationNotSupportedErrror (impersonatedUser, fn) { const recorder = new utils.MessageRecordingConnection() @@ -69,7 +69,7 @@ describe('#unit BoltProtocolV2', () => { } describe('beginTransaction', () => { - function verifyBeginTransaction(impersonatedUser) { + function verifyBeginTransaction (impersonatedUser) { verifyImpersonationNotSupportedErrror( impersonatedUser, protocol => protocol.beginTransaction({ impersonatedUser })) @@ -104,7 +104,7 @@ describe('#unit BoltProtocolV2', () => { const parameters = { x: 'x', y: 'y' } const observer = protocol.run(query, parameters, { lowRecordWatermark: 100, - highRecordWatermark: 200, + highRecordWatermark: 200 }) expect(observer._lowRecordWatermark).toEqual(100) diff --git a/packages/bolt-connection/test/bolt/bolt-protocol-v3.test.js b/packages/bolt-connection/test/bolt/bolt-protocol-v3.test.js index 02ba8a712..205ced51a 100644 --- a/packages/bolt-connection/test/bolt/bolt-protocol-v3.test.js +++ b/packages/bolt-connection/test/bolt/bolt-protocol-v3.test.js @@ -237,7 +237,7 @@ describe('#unit BoltProtocolV3', () => { describe('Bolt v4.4', () => { /** * @param {string} impersonatedUser The impersonated user. - * @param {function(protocol: BoltProtocolV3)} fn + * @param {function(protocol: BoltProtocolV3)} fn */ function verifyImpersonationNotSupportedErrror (impersonatedUser, fn) { const recorder = new utils.MessageRecordingConnection() @@ -251,7 +251,7 @@ describe('#unit BoltProtocolV3', () => { } describe('beginTransaction', () => { - function verifyBeginTransaction(impersonatedUser) { + function verifyBeginTransaction (impersonatedUser) { verifyImpersonationNotSupportedErrror( impersonatedUser, protocol => protocol.beginTransaction({ impersonatedUser })) @@ -309,7 +309,7 @@ describe('#unit BoltProtocolV3', () => { bookmarks: Bookmarks.empty(), txConfig: TxConfig.empty(), lowRecordWatermark: 100, - highRecordWatermark: 200, + highRecordWatermark: 200 }) expect(observer._lowRecordWatermark).toEqual(100) diff --git a/packages/bolt-connection/test/bolt/bolt-protocol-v4x0.test.js b/packages/bolt-connection/test/bolt/bolt-protocol-v4x0.test.js index 22a1ca93d..819eaa932 100644 --- a/packages/bolt-connection/test/bolt/bolt-protocol-v4x0.test.js +++ b/packages/bolt-connection/test/bolt/bolt-protocol-v4x0.test.js @@ -152,11 +152,11 @@ describe('#unit BoltProtocolV4x0', () => { { ...sessionContext, txConfig: TxConfig.empty() } ]) }) - + describe('Bolt v4.4', () => { /** * @param {string} impersonatedUser The impersonated user. - * @param {function(protocol: BoltProtocolV4x0)} fn + * @param {function(protocol: BoltProtocolV4x0)} fn */ function verifyImpersonationNotSupportedErrror (impersonatedUser, fn) { const recorder = new utils.MessageRecordingConnection() @@ -170,7 +170,7 @@ describe('#unit BoltProtocolV4x0', () => { } describe('beginTransaction', () => { - function verifyBeginTransaction(impersonatedUser) { + function verifyBeginTransaction (impersonatedUser) { verifyImpersonationNotSupportedErrror( impersonatedUser, protocol => protocol.beginTransaction({ impersonatedUser })) @@ -228,7 +228,7 @@ describe('#unit BoltProtocolV4x0', () => { bookmarks: Bookmarks.empty(), txConfig: TxConfig.empty(), lowRecordWatermark: 100, - highRecordWatermark: 200, + highRecordWatermark: 200 }) expect(observer._lowRecordWatermark).toEqual(100) diff --git a/packages/bolt-connection/test/bolt/bolt-protocol-v4x1.test.js b/packages/bolt-connection/test/bolt/bolt-protocol-v4x1.test.js index 9bf646094..545ea97dd 100644 --- a/packages/bolt-connection/test/bolt/bolt-protocol-v4x1.test.js +++ b/packages/bolt-connection/test/bolt/bolt-protocol-v4x1.test.js @@ -30,7 +30,7 @@ describe('#unit BoltProtocolV4x1', () => { describe('Bolt v4.4', () => { /** * @param {string} impersonatedUser The impersonated user. - * @param {function(protocol: BoltProtocolV4x1)} fn + * @param {function(protocol: BoltProtocolV4x1)} fn */ function verifyImpersonationNotSupportedErrror (impersonatedUser, fn) { const recorder = new utils.MessageRecordingConnection() @@ -44,7 +44,7 @@ describe('#unit BoltProtocolV4x1', () => { } describe('beginTransaction', () => { - function verifyBeginTransaction(impersonatedUser) { + function verifyBeginTransaction (impersonatedUser) { verifyImpersonationNotSupportedErrror( impersonatedUser, protocol => protocol.beginTransaction({ impersonatedUser })) @@ -102,7 +102,7 @@ describe('#unit BoltProtocolV4x1', () => { bookmarks: Bookmarks.empty(), txConfig: TxConfig.empty(), lowRecordWatermark: 100, - highRecordWatermark: 200, + highRecordWatermark: 200 }) expect(observer._lowRecordWatermark).toEqual(100) diff --git a/packages/bolt-connection/test/bolt/bolt-protocol-v4x2.test.js b/packages/bolt-connection/test/bolt/bolt-protocol-v4x2.test.js index d754c3d0e..6a7604bda 100644 --- a/packages/bolt-connection/test/bolt/bolt-protocol-v4x2.test.js +++ b/packages/bolt-connection/test/bolt/bolt-protocol-v4x2.test.js @@ -30,7 +30,7 @@ describe('#unit BoltProtocolV4x2', () => { describe('Bolt v4.4', () => { /** * @param {string} impersonatedUser The impersonated user. - * @param {function(protocol: BoltProtocolV4x2)} fn + * @param {function(protocol: BoltProtocolV4x2)} fn */ function verifyImpersonationNotSupportedErrror (impersonatedUser, fn) { const recorder = new utils.MessageRecordingConnection() @@ -44,7 +44,7 @@ describe('#unit BoltProtocolV4x2', () => { } describe('beginTransaction', () => { - function verifyBeginTransaction(impersonatedUser) { + function verifyBeginTransaction (impersonatedUser) { verifyImpersonationNotSupportedErrror( impersonatedUser, protocol => protocol.beginTransaction({ impersonatedUser })) @@ -101,7 +101,7 @@ describe('#unit BoltProtocolV4x2', () => { bookmarks: Bookmarks.empty(), txConfig: TxConfig.empty(), lowRecordWatermark: 100, - highRecordWatermark: 200, + highRecordWatermark: 200 }) expect(observer._lowRecordWatermark).toEqual(100) diff --git a/packages/bolt-connection/test/bolt/bolt-protocol-v4x3.test.js b/packages/bolt-connection/test/bolt/bolt-protocol-v4x3.test.js index a140de671..fc3b846b8 100644 --- a/packages/bolt-connection/test/bolt/bolt-protocol-v4x3.test.js +++ b/packages/bolt-connection/test/bolt/bolt-protocol-v4x3.test.js @@ -241,7 +241,7 @@ describe('#unit BoltProtocolV4x3', () => { describe('Bolt v4.4', () => { /** * @param {string} impersonatedUser The impersonated user. - * @param {function(protocol: BoltProtocolV4x3)} fn + * @param {function(protocol: BoltProtocolV4x3)} fn */ function verifyImpersonationNotSupportedErrror (impersonatedUser, fn) { const recorder = new utils.MessageRecordingConnection() @@ -255,7 +255,7 @@ describe('#unit BoltProtocolV4x3', () => { } describe('beginTransaction', () => { - function verifyBeginTransaction(impersonatedUser) { + function verifyBeginTransaction (impersonatedUser) { verifyImpersonationNotSupportedErrror( impersonatedUser, protocol => protocol.beginTransaction({ impersonatedUser })) @@ -313,7 +313,7 @@ describe('#unit BoltProtocolV4x3', () => { bookmarks: Bookmarks.empty(), txConfig: TxConfig.empty(), lowRecordWatermark: 100, - highRecordWatermark: 200, + highRecordWatermark: 200 }) expect(observer._lowRecordWatermark).toEqual(100) diff --git a/packages/bolt-connection/test/bolt/bolt-protocol-v4x4.test.js b/packages/bolt-connection/test/bolt/bolt-protocol-v4x4.test.js index a44bfb717..d4f779b16 100644 --- a/packages/bolt-connection/test/bolt/bolt-protocol-v4x4.test.js +++ b/packages/bolt-connection/test/bolt/bolt-protocol-v4x4.test.js @@ -73,7 +73,7 @@ describe('#unit BoltProtocolV4x4', () => { protocol.verifyMessageCount(1) expect(protocol.messages[0]).toBeMessage( - RequestMessage.routeV4x4(routingContext, listOfBookmarks, { databaseName, impersonatedUser: null}) + RequestMessage.routeV4x4(routingContext, listOfBookmarks, { databaseName, impersonatedUser: null }) ) expect(protocol.observers).toEqual([observer]) expect(observer).toEqual(expect.any(RouteObserver)) @@ -346,7 +346,7 @@ describe('#unit BoltProtocolV4x4', () => { bookmarks: Bookmarks.empty(), txConfig: TxConfig.empty(), lowRecordWatermark: 100, - highRecordWatermark: 200, + highRecordWatermark: 200 }) expect(observer._lowRecordWatermark).toEqual(100) diff --git a/packages/bolt-connection/test/bolt/bolt-protocol-v5x0.test.js b/packages/bolt-connection/test/bolt/bolt-protocol-v5x0.test.js index f8b4ed95a..512918bd3 100644 --- a/packages/bolt-connection/test/bolt/bolt-protocol-v5x0.test.js +++ b/packages/bolt-connection/test/bolt/bolt-protocol-v5x0.test.js @@ -74,7 +74,7 @@ describe('#unit BoltProtocolV5x0', () => { protocol.verifyMessageCount(1) expect(protocol.messages[0]).toBeMessage( - RequestMessage.routeV4x4(routingContext, listOfBookmarks, { databaseName, impersonatedUser: null}) + RequestMessage.routeV4x4(routingContext, listOfBookmarks, { databaseName, impersonatedUser: null }) ) expect(protocol.observers).toEqual([observer]) expect(observer).toEqual(expect.any(RouteObserver)) @@ -347,7 +347,7 @@ describe('#unit BoltProtocolV5x0', () => { bookmarks: Bookmarks.empty(), txConfig: TxConfig.empty(), lowRecordWatermark: 100, - highRecordWatermark: 200, + highRecordWatermark: 200 }) expect(observer._lowRecordWatermark).toEqual(100) diff --git a/packages/bolt-connection/test/bolt/request-message.test.js b/packages/bolt-connection/test/bolt/request-message.test.js index 4e6ec5b1c..f0f66dd68 100644 --- a/packages/bolt-connection/test/bolt/request-message.test.js +++ b/packages/bolt-connection/test/bolt/request-message.test.js @@ -175,7 +175,7 @@ describe('#unit RequestMessage', () => { }) describe('BoltV4', () => { - function verify(message, signature, metadata, name) { + function verify (message, signature, metadata, name) { expect(message.signature).toEqual(signature) expect(message.fields).toEqual([metadata]) expect(message.toString()).toEqual(`${name} ${json.stringify(metadata)}`) @@ -272,7 +272,7 @@ describe('#unit RequestMessage', () => { const requestContext = { someValue: '1234' } const bookmarks = ['a', 'b'] const databaseName = 'user_db' - const impersonatedUser = "user" + const impersonatedUser = 'user' const message = RequestMessage.routeV4x4(requestContext, bookmarks, { databaseName, impersonatedUser }) diff --git a/packages/bolt-connection/test/bolt/routing-table-raw.test.js b/packages/bolt-connection/test/bolt/routing-table-raw.test.js index d9bd2ff62..6789a7e81 100644 --- a/packages/bolt-connection/test/bolt/routing-table-raw.test.js +++ b/packages/bolt-connection/test/bolt/routing-table-raw.test.js @@ -142,7 +142,6 @@ describe('#unit RawRoutingTable', () => { const result = RawRoutingTable.ofRecord(record) expect(result.db).toEqual(null) }) - }) }) diff --git a/packages/bolt-connection/test/bolt/stream-observer.test.js b/packages/bolt-connection/test/bolt/stream-observer.test.js index e637c15fa..3431528b1 100644 --- a/packages/bolt-connection/test/bolt/stream-observer.test.js +++ b/packages/bolt-connection/test/bolt/stream-observer.test.js @@ -434,10 +434,8 @@ describe('#unit ResultStreamObserver', () => { expect(more).toBeCalledWith(queryId, fetchSize, streamObserver) }) - it('should ask for more records when the stream is a new reactive stream and not run success come yet', () => { // Setup - const queryId = 123 const fetchSize = 2000 const more = jest.fn() @@ -479,7 +477,6 @@ describe('#unit ResultStreamObserver', () => { expect(more).toBeCalledTimes(0) }) - it('should not ask for more records when the stream is a new stream', () => { // Setup const queryId = 123 @@ -565,7 +562,6 @@ describe('#unit ResultStreamObserver', () => { expect(more).toBeCalledTimes(0) }) - it('should resume the stream consumption until the end', () => { // Setup const queryId = 123 @@ -646,7 +642,7 @@ describe('#unit ResultStreamObserver', () => { ['undefined'], ['null'], ['banana'] - ])(`should trigger onError when the type is '%s'`, (type) => { + ])('should trigger onError when the type is \'%s\'', (type) => { const streamObserver = newStreamObserver() const expectedError = newError( `Server returned invalid query type. Expected one of [undefined, null, "r", "w", "rw", "s"] but got '${type}'`, @@ -671,7 +667,7 @@ describe('#unit ResultStreamObserver', () => { ['s'], [null], [undefined] - ])(`should trigger onComplete when the type is '%s'`, (type) => { + ])('should trigger onComplete when the type is \'%s\'', (type) => { const streamObserver = newStreamObserver() streamObserver.onCompleted({ fields: ['A', 'B', 'C'] }) diff --git a/packages/bolt-connection/test/channel/browser/browser-channel.test.js b/packages/bolt-connection/test/channel/browser/browser-channel.test.js index d9e0aa7a8..1011d76a7 100644 --- a/packages/bolt-connection/test/channel/browser/browser-channel.test.js +++ b/packages/bolt-connection/test/channel/browser/browser-channel.test.js @@ -31,6 +31,7 @@ const { SERVICE_UNAVAILABLE } = error const WS_CONNECTING = 0 const WS_OPEN = 1 +// eslint-disable-next-line no-unused-vars const WS_CLOSING = 2 const WS_CLOSED = 3 diff --git a/packages/bolt-connection/test/channel/encode-decode.test.js b/packages/bolt-connection/test/channel/encode-decode.test.js index 18b4c1969..884bf8eed 100644 --- a/packages/bolt-connection/test/channel/encode-decode.test.js +++ b/packages/bolt-connection/test/channel/encode-decode.test.js @@ -36,7 +36,7 @@ describe('uft8', () => { '⚡ 🏃‍♀️' ])('should decode encoded string', str => { const encoded = encode(str) - + const encodedThenDecoded = decode(encoded, encoded.length) expect(encodedThenDecoded).toEqual(str) @@ -54,12 +54,11 @@ describe('uft8', () => { '⚡ 🏃‍♀️' ])('.encode("%s") should match snapshot', str => { const encoded = encode(str) - + expect(encoded.toString()).toMatchSnapshot() }) }) - -function makeString ( len ) { +function makeString (len) { return crypto.randomBytes(len).toString('hex') } diff --git a/packages/bolt-connection/test/channel/node/node-channel.test.js b/packages/bolt-connection/test/channel/node/node-channel.test.js index fa9bab622..c36473ead 100644 --- a/packages/bolt-connection/test/channel/node/node-channel.test.js +++ b/packages/bolt-connection/test/channel/node/node-channel.test.js @@ -120,7 +120,7 @@ describe('NodeChannel', () => { expect(channel._conn.getCalls().setTimeout[1]).toEqual([receiveTimeout]) }) - it ('should not call socket.setTimeout(receiveTimeout) if stream already started', () => { + it('should not call socket.setTimeout(receiveTimeout) if stream already started', () => { const { receiveTimeout, channel } = setup() // setup @@ -135,7 +135,7 @@ describe('NodeChannel', () => { expect(channel._conn.getCalls().setTimeout[1]).toEqual([receiveTimeout]) }) - it ('should call socket.setTimeout(receiveTimeout) when after stop', () => { + it('should call socket.setTimeout(receiveTimeout) when after stop', () => { const { receiveTimeout, channel } = setup() // setup @@ -157,12 +157,12 @@ describe('NodeChannel', () => { const channel = createMockedChannel(true) const receiveTimeout = 42 channel.setupReceiveTimeout(receiveTimeout) - return {channel, receiveTimeout} + return { channel, receiveTimeout } } }) describe('receive timemout is not setup', () => { - it ('should call not socket.setTimeout(receiveTimeout) when not started', () => { + it('should call not socket.setTimeout(receiveTimeout) when not started', () => { const channel = createMockedChannel(true) // start again @@ -175,7 +175,7 @@ describe('NodeChannel', () => { describe('.stopReceiveTimeout()', () => { describe('when receive timeout is setup', () => { - it ('should not call socket.setTimeout(0) when not started', () => { + it('should not call socket.setTimeout(0) when not started', () => { const { channel } = setup() channel.stopReceiveTimeout() @@ -183,7 +183,7 @@ describe('NodeChannel', () => { expect(channel._conn.getCalls().setTimeout.length).toEqual(1) }) - it ('should call socket.setTimeout(0) when already started', () => { + it('should call socket.setTimeout(0) when already started', () => { const { channel } = setup() channel.startReceiveTimeout() @@ -194,7 +194,7 @@ describe('NodeChannel', () => { expect(channel._conn.getCalls().setTimeout[2]).toEqual([0]) }) - it ('should not call socket.setTimeout(0) when already stopped', () => { + it('should not call socket.setTimeout(0) when already stopped', () => { const { channel } = setup() channel.startReceiveTimeout() @@ -209,12 +209,12 @@ describe('NodeChannel', () => { const channel = createMockedChannel(true) const receiveTimeout = 42 channel.setupReceiveTimeout(receiveTimeout) - return {channel, receiveTimeout} + return { channel, receiveTimeout } } }) describe('when receive timeout is not setup', () => { - it ('should not call socket.setTimeout(0)', () => { + it('should not call socket.setTimeout(0)', () => { const channel = createMockedChannel(true) channel.startReceiveTimeout() diff --git a/packages/bolt-connection/test/connection-provider/connection-provider-direct.test.js b/packages/bolt-connection/test/connection-provider/connection-provider-direct.test.js index ef0ba5c4a..6abc03082 100644 --- a/packages/bolt-connection/test/connection-provider/connection-provider-direct.test.js +++ b/packages/bolt-connection/test/connection-provider/connection-provider-direct.test.js @@ -243,7 +243,7 @@ describe('.verifyConnectivityAndGetServerInfo()', () => { }) }) - function setup({ releaseMock } = {}) { + function setup ({ releaseMock } = {}) { const protocolVersion = 4.4 const resetAndFlush = jest.fn(() => Promise.resolve()) const server = { address: 'localhost:123', version: 'neo4j/1234' } @@ -278,14 +278,14 @@ describe('.verifyConnectivityAndGetServerInfo()', () => { const address = ServerAddress.fromUrl('localhost:123') const pool = newPool({ config: { - acquisitionTimeout: 0, + acquisitionTimeout: 0 } }) const connectionProvider = newDirectConnectionProvider(address, pool) try { - connectionProvider = await connectionProvider.verifyConnectivityAndGetServerInfo() + await connectionProvider.verifyConnectivityAndGetServerInfo() expect().toBe('not reached') } catch (e) { expect(e).toBeDefined() @@ -304,7 +304,7 @@ describe('.verifyConnectivityAndGetServerInfo()', () => { const connectionProvider = newDirectConnectionProvider(address, pool) try { - connectionProvider = await connectionProvider.verifyConnectivityAndGetServerInfo() + await connectionProvider.verifyConnectivityAndGetServerInfo() expect().toBe('not reached') } catch (e) { expect(e).toBe(error) @@ -324,7 +324,7 @@ function newDirectConnectionProvider (address, pool) { return connectionProvider } -function newPool({ create, config } = {}) { +function newPool ({ create, config } = {}) { const _create = (address, release) => { if (create) { return create(address, release) @@ -334,12 +334,12 @@ function newPool({ create, config } = {}) { return new Pool({ config, create: (address, release) => - Promise.resolve(_create(address, release)), + Promise.resolve(_create(address, release)) }) } class FakeConnection extends Connection { - constructor(address, release, server) { + constructor (address, release, server) { super(null) this._address = address @@ -347,11 +347,11 @@ class FakeConnection extends Connection { this._server = server } - get address() { + get address () { return this._address } - get server() { + get server () { return this._server } } diff --git a/packages/bolt-connection/test/connection-provider/connection-provider-routing.test.js b/packages/bolt-connection/test/connection-provider/connection-provider-routing.test.js index d94d866e2..e1b297229 100644 --- a/packages/bolt-connection/test/connection-provider/connection-provider-routing.test.js +++ b/packages/bolt-connection/test/connection-provider/connection-provider-routing.test.js @@ -70,8 +70,6 @@ describe('#unit RoutingConnectionProvider', () => { const serverDD = ServerAddress.fromUrl('serverDD') const serverEE = ServerAddress.fromUrl('serverEE') - const serverABC = ServerAddress.fromUrl('serverABC') - const usersDataSet = [ [null], [undefined], @@ -1700,8 +1698,8 @@ describe('#unit RoutingConnectionProvider', () => { } catch (capturedError) { expect(capturedError.code).toBe(SERVICE_UNAVAILABLE) expect(capturedError.message).toBe( - 'Server at server-non-existing-seed-router:7687 can\'t ' - + 'perform routing. Make sure you are connecting to a causal cluster' + 'Server at server-non-existing-seed-router:7687 can\'t ' + + 'perform routing. Make sure you are connecting to a causal cluster' ) } @@ -1734,7 +1732,6 @@ describe('#unit RoutingConnectionProvider', () => { expect(completed).toBe(false) }) - }) }) @@ -2224,7 +2221,7 @@ describe('#unit RoutingConnectionProvider', () => { }, 10000) it.each(usersDataSet)('should purge expired routing tables after specified duration on update [user=%s]', async (user) => { - var originalDateNow = Date.now + const originalDateNow = Date.now Date.now = () => 50000 try { const routingTableToLoad = newRoutingTable( @@ -2315,11 +2312,11 @@ describe('#unit RoutingConnectionProvider', () => { const connectionProvider = newRoutingConnectionProvider( [], pool, - { + { null: { 'server-non-existing-seed-router:7687': newRoutingTableWithUser( { - database: null, + database: null, routers: [server1, server2, server3], readers: [server1, server2], writers: [server3], @@ -2327,7 +2324,7 @@ describe('#unit RoutingConnectionProvider', () => { routingTableDatabase: 'homedb' } ) - } + } } ) @@ -2349,11 +2346,11 @@ describe('#unit RoutingConnectionProvider', () => { const connectionProvider = newRoutingConnectionProvider( [], pool, - { - 'databaseA': { + { + databaseA: { 'server-non-existing-seed-router:7687': newRoutingTableWithUser( { - database: 'databaseA', + database: 'databaseA', routers: [server1, server3], readers: [server1], writers: [server3], @@ -2362,10 +2359,10 @@ describe('#unit RoutingConnectionProvider', () => { } ) }, - 'databaseB': { + databaseB: { 'server-non-existing-seed-router:7687': newRoutingTableWithUser( { - database: 'homedb', + database: 'homedb', routers: [server2, server3], readers: [server2], writers: [server3], @@ -2373,7 +2370,7 @@ describe('#unit RoutingConnectionProvider', () => { routingTableDatabase: 'homedb' } ) - } + } } ) @@ -2409,14 +2406,13 @@ describe('#unit RoutingConnectionProvider', () => { } ) - await connectionProvider.acquireConnection({ accessMode: READ, impersonatedUser: user, accessMode: WRITE }) + await connectionProvider.acquireConnection({ accessMode: WRITE, impersonatedUser: user }) const connection = await connectionProvider.acquireConnection({ accessMode: READ, database: 'homedb', impersonatedUser: user }) expect(connection.address).toEqual(server1) expect(pool.has(server1)).toBeTruthy() }) - it('should be to acquire connection other users homedb using it name', async () => { const user1 = 'the-impostor-number-1' const user2 = 'the-impostor-number-2' @@ -2467,15 +2463,14 @@ describe('#unit RoutingConnectionProvider', () => { ) ] }, - "kakakaka": {} - }, + kakakaka: {} + } ) await connectionProvider.acquireConnection({ accessMode: WRITE, impersonatedUser: user2 }) await connectionProvider.acquireConnection({ accessMode: WRITE, impersonatedUser: user1 }) await connectionProvider.acquireConnection({ accessMode: WRITE }) - const defaultConnToHomeDb1 = await connectionProvider.acquireConnection({ accessMode: READ, database: 'homedb1' }) expect(defaultConnToHomeDb1.address).toEqual(server1) expect(pool.has(server1)).toBeTruthy() @@ -2499,10 +2494,8 @@ describe('#unit RoutingConnectionProvider', () => { const user2ConnToHomeDb1 = await connectionProvider.acquireConnection({ accessMode: READ, database: 'homedb1', impersonatedUser: user2 }) expect(user2ConnToHomeDb1.address).toEqual(server1) expect(pool.has(server1)).toBeTruthy() - }) - it.each(usersDataSet)('should call onDatabaseNameResolved with the resolved db acquiring home db [user=%s]', async (user) => { const pool = newPool() const connectionProvider = newRoutingConnectionProvider( @@ -2534,7 +2527,7 @@ describe('#unit RoutingConnectionProvider', () => { [], pool, { - 'databaseA': { + databaseA: { 'server-non-existing-seed-router:7687': newRoutingTableWithUser({ database: 'databaseA', routers: [server1, server2, server3], @@ -2553,7 +2546,6 @@ describe('#unit RoutingConnectionProvider', () => { expect(onDatabaseNameResolved).toHaveBeenCalledWith('databaseA') }) - }) describe.each([ @@ -2562,7 +2554,7 @@ describe('#unit RoutingConnectionProvider', () => { ['', READ], ['', WRITE], ['databaseA', READ], - ['databaseA', WRITE], + ['databaseA', WRITE] ])('.verifyConnectivityAndGetServeInfo({ database: %s, accessMode: %s })', (database, accessMode) => { describe('when connection is available in the pool', () => { it('should return the server info', async () => { @@ -2590,7 +2582,6 @@ describe('#unit RoutingConnectionProvider', () => { expect(connections[0]._release).toHaveBeenCalled() expect(connections[0]._release.mock.invocationCallOrder[0]) .toBeGreaterThan(connections[0].resetAndFlush.mock.invocationCallOrder[0]) - }) it('should not acquire, resetAndFlush and release connections for sever with the other access mode', async () => { @@ -2610,18 +2601,18 @@ describe('#unit RoutingConnectionProvider', () => { it('should succeed with the server info ', async () => { const error = newError('Error') let i = 0 - const resetAndFlush = jest.fn(() => i++ % 2 == 0 ? Promise.reject(error) : Promise.resolve()) + const resetAndFlush = jest.fn(() => i++ % 2 === 0 ? Promise.reject(error) : Promise.resolve()) const { connectionProvider, server, protocolVersion } = setup({ resetAndFlush }) const serverInfo = await connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode }) - + expect(serverInfo).toEqual(new ServerInfo(server, protocolVersion)) }) it('should release the connection', async () => { const error = newError('Error') let i = 0 - const resetAndFlush = jest.fn(() => i++ % 2 == 0 ? Promise.reject(error) : Promise.resolve()) + const resetAndFlush = jest.fn(() => i++ % 2 === 0 ? Promise.reject(error) : Promise.resolve()) const { connectionProvider, seenConnectionsPerAddress, routingTable } = setup({ resetAndFlush }) try { @@ -2644,7 +2635,7 @@ describe('#unit RoutingConnectionProvider', () => { const error = newError('Error') const releaseError = newError('Release error') let i = 0 - const resetAndFlush = jest.fn(() => i++ % 2 == 0 ? Promise.reject(error) : Promise.resolve()) + const resetAndFlush = jest.fn(() => i++ % 2 === 0 ? Promise.reject(error) : Promise.resolve()) const releaseMock = jest.fn(() => Promise.reject(releaseError)) const { connectionProvider } = setup({ resetAndFlush, releaseMock }) @@ -2666,8 +2657,8 @@ describe('#unit RoutingConnectionProvider', () => { try { await connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode }) - expect().toBe('Not reached') - } catch(e) { + expect().toBe('Not reached') + } catch (e) { expect(e).toBe(error) } }) @@ -2676,7 +2667,7 @@ describe('#unit RoutingConnectionProvider', () => { const resetAndFlush = jest.fn(() => Promise.reject(error)) const { connectionProvider, routingTable, seenConnectionsPerAddress, pool } = setup({ resetAndFlush }) const acquireSpy = jest.spyOn(pool, 'acquire') - + try { await connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode }) } catch (e) { @@ -2685,9 +2676,9 @@ describe('#unit RoutingConnectionProvider', () => { const targetServers = accessMode === WRITE ? routingTable.writers : routingTable.readers for (const address of targetServers) { expect(acquireSpy).toHaveBeenCalledWith(address) - + const connections = seenConnectionsPerAddress.get(address) - + expect(connections.length).toBe(1) expect(connections[0].resetAndFlush).toHaveBeenCalled() expect(connections[0]._release).toHaveBeenCalled() @@ -2700,7 +2691,7 @@ describe('#unit RoutingConnectionProvider', () => { it('should release the connection', async () => { const error = newError('Error') let i = 0 - const resetAndFlush = jest.fn(() => i++ % 2 == 0 ? Promise.reject(error) : Promise.resolve()) + const resetAndFlush = jest.fn(() => i++ % 2 === 0 ? Promise.reject(error) : Promise.resolve()) const { connectionProvider, seenConnectionsPerAddress, routingTable } = setup({ resetAndFlush }) try { @@ -2723,7 +2714,7 @@ describe('#unit RoutingConnectionProvider', () => { const error = newError('Error') const releaseError = newError('Release error') let i = 0 - const resetAndFlush = jest.fn(() => i++ % 2 == 0 ? Promise.reject(error) : Promise.resolve()) + const resetAndFlush = jest.fn(() => i++ % 2 === 0 ? Promise.reject(error) : Promise.resolve()) const releaseMock = jest.fn(() => Promise.reject(releaseError)) const { connectionProvider } = setup({ resetAndFlush, releaseMock }) @@ -2735,17 +2726,16 @@ describe('#unit RoutingConnectionProvider', () => { } }) }) - }) describe('when the release for at least one the address', () => { it('should succeed with the server info', async () => { const error = newError('Error') let i = 0 - const releaseMock = jest.fn(() => i++ % 2 == 0 ? Promise.reject(error) : Promise.resolve()) + const releaseMock = jest.fn(() => i++ % 2 === 0 ? Promise.reject(error) : Promise.resolve()) const { connectionProvider, server, protocolVersion } = setup({ releaseMock }) - const serverInfo = await connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode }) + const serverInfo = await connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode }) expect(serverInfo).toEqual(new ServerInfo(server, protocolVersion)) }) @@ -2760,13 +2750,13 @@ describe('#unit RoutingConnectionProvider', () => { try { await connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode }) expect().toBe('Not reached') - } catch(e) { + } catch (e) { expect(e).toBe(error) } }) }) - function setup({ resetAndFlush, releaseMock } = {}) { + function setup ({ resetAndFlush, releaseMock } = {}) { const routingTable = newRoutingTable( database || null, [server1, server2], @@ -2815,7 +2805,7 @@ describe('#unit RoutingConnectionProvider', () => { const pool = newPool({ config: { - acquisitionTimeout: 0, + acquisitionTimeout: 0 } }) @@ -2827,7 +2817,7 @@ describe('#unit RoutingConnectionProvider', () => { ) try { - connectionProvider = await connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode }) + await connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode }) expect().toBe('not reached') } catch (e) { expect(e).toBeDefined() @@ -2862,7 +2852,7 @@ describe('#unit RoutingConnectionProvider', () => { pool ) - const serverInfo = connectionProvider = await connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode }) + const serverInfo = await connectionProvider.verifyConnectivityAndGetServerInfo({ database, accessMode }) expect(serverInfo).toEqual(new ServerInfo({}, 4.4)) }) }) @@ -2994,7 +2984,7 @@ function newRoutingTable ( expirationTime = Integer.MAX_VALUE, routingTableDatabase ) { - var routingTable = new RoutingTable({ + const routingTable = new RoutingTable({ database: database || routingTableDatabase, routers, readers, @@ -3031,7 +3021,7 @@ function newPool ({ create, config } = {}) { } return new Pool({ config, - create: (address, release) => _create(address, release), + create: (address, release) => _create(address, release) }) } @@ -3070,7 +3060,7 @@ class FakeConnection extends Connection { super(null) this._address = address - this._version = version || VERSION_IN_DEV.toString() + this._version = version this._protocolVersion = protocolVersion this.release = release this._release = jest.fn(() => release(address, this)) @@ -3109,7 +3099,7 @@ class FakeRediscovery { } const table = this._routerToRoutingTable[database || null] if (table) { - let routingTables = table[router.asKey()] + const routingTables = table[router.asKey()] let routingTable = routingTables if (routingTables instanceof Array) { routingTable = routingTables.find(rt => rt.user === user) diff --git a/packages/bolt-connection/test/connection/connection-channel.test.js b/packages/bolt-connection/test/connection/connection-channel.test.js index 3a7797fca..c1acd5ce8 100644 --- a/packages/bolt-connection/test/connection/connection-channel.test.js +++ b/packages/bolt-connection/test/connection/connection-channel.test.js @@ -129,9 +129,9 @@ describe('ChannelConnection', () => { describe('._handleFatalError()', () => { describe('when there is not current failure on going', () => { const thrownError = newError('some error', 'C') - let loggerFunction; - let notifyFatalError; - let connection; + let loggerFunction + let notifyFatalError + let connection beforeEach(() => { notifyFatalError = jest.fn() @@ -177,9 +177,9 @@ describe('ChannelConnection', () => { describe('when there is current failure on going', () => { const thrownError = newError('some error', 'C') const currentFailure = newError('current failure', 'ongoing') - let loggerFunction; - let notifyFatalError; - let connection; + let loggerFunction + let notifyFatalError + let connection beforeEach(() => { notifyFatalError = jest.fn() diff --git a/packages/bolt-connection/test/connection/connection-error-handler.test.js b/packages/bolt-connection/test/connection/connection-error-handler.test.js index f526e1c4c..ba299be38 100644 --- a/packages/bolt-connection/test/connection/connection-error-handler.test.js +++ b/packages/bolt-connection/test/connection/connection-error-handler.test.js @@ -140,7 +140,6 @@ describe('#unit ConnectionErrorHandler', () => { expect(addresses).toEqual([]) }) - it('should handle and transform token expired error', () => { const errors = [] const addresses = [] diff --git a/packages/bolt-connection/test/packstream/packstream-v5.test.js b/packages/bolt-connection/test/packstream/packstream-v5.test.js index cd38f214e..ffb9df042 100644 --- a/packages/bolt-connection/test/packstream/packstream-v5.test.js +++ b/packages/bolt-connection/test/packstream/packstream-v5.test.js @@ -17,11 +17,10 @@ * limitations under the License. */ -import { int, Integer } from 'neo4j-driver-core' +import { int, Integer, Node, Relationship, UnboundRelationship } from 'neo4j-driver-core' import { alloc } from '../../src/channel' import { Packer, Unpacker } from '../../src/packstream/packstream-v5' import { Structure } from '../../src/packstream/packstream-v1' -import { Node, int, Relationship, UnboundRelationship } from 'neo4j-driver-core' describe('#unit PackStreamV5', () => { it('should pack integers with small numbers', () => { @@ -226,11 +225,11 @@ describe('#unit PackStreamV5', () => { expect(() => packAndUnpack(struct)).toThrow() }) - function validNodesAndConfig() { - function validWithNumber() { + function validNodesAndConfig () { + function validWithNumber () { const identity = 1 const labels = ['a', 'b'] - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const expectedNode = new Node(identity, labels, properties, elementId) const nodeStruct = new Structure(0x4e, [ @@ -239,10 +238,10 @@ describe('#unit PackStreamV5', () => { return [nodeStruct, expectedNode, { disableLosslessIntegers: true, useBigInt: false }] } - function validWithoutOldIdentifiersLossy() { + function validWithoutOldIdentifiersLossy () { const identity = null const labels = ['a', 'b'] - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const expectedNode = new Node(-1, labels, properties, elementId) const nodeStruct = new Structure(0x4e, [ @@ -251,10 +250,10 @@ describe('#unit PackStreamV5', () => { return [nodeStruct, expectedNode, { disableLosslessIntegers: true, useBigInt: false }] } - function validWithoutOldIdentifiersLosslessInteger() { + function validWithoutOldIdentifiersLosslessInteger () { const identity = null const labels = ['a', 'b'] - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const expectedNode = new Node(int(-1), labels, properties, elementId) const nodeStruct = new Structure(0x4e, [ @@ -263,10 +262,10 @@ describe('#unit PackStreamV5', () => { return [nodeStruct, expectedNode, { disableLosslessIntegers: false, useBigInt: false }] } - function validWithoutOldIdentifiersBigInt() { + function validWithoutOldIdentifiersBigInt () { const identity = null const labels = ['a', 'b'] - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const expectedNode = new Node(BigInt(-1), labels, properties, elementId) const nodeStruct = new Structure(0x4e, [ @@ -275,10 +274,10 @@ describe('#unit PackStreamV5', () => { return [nodeStruct, expectedNode, { disableLosslessIntegers: false, useBigInt: true }] } - function validWithInt() { + function validWithInt () { const identity = int(1) const labels = ['a', 'b'] - const properties = { 'a': int(1), 'b': int(2) } + const properties = { a: int(1), b: int(2) } const elementId = 'element_id_1' const expectedNode = new Node(identity, labels, properties, elementId) const nodeStruct = new Structure(0x4e, [ @@ -287,10 +286,10 @@ describe('#unit PackStreamV5', () => { return [nodeStruct, expectedNode, { disableLosslessIntegers: false, useBigInt: false }] } - function validWithBigInt() { + function validWithBigInt () { const identity = BigInt(1) const labels = ['a', 'b'] - const properties = { 'a': BigInt(1), 'b': BigInt(2) } + const properties = { a: BigInt(1), b: BigInt(2) } const elementId = 'element_id_1' const expectedNode = new Node(identity, labels, properties, elementId) const nodeStruct = new Structure(0x4e, [ @@ -309,20 +308,20 @@ describe('#unit PackStreamV5', () => { ] } - function invalidNodesConfig() { + function invalidNodesConfig () { return [ - [new Structure(0x4e, [1, ['a', 'b'], { 'a': 1, 'b': 2 }])], - [new Structure(0x4e, [1, ['a', 'b'], { 'a': 1, 'b': 2 }, 'elementId', 'myId'])], + [new Structure(0x4e, [1, ['a', 'b'], { a: 1, b: 2 }])], + [new Structure(0x4e, [1, ['a', 'b'], { a: 1, b: 2 }, 'elementId', 'myId'])] ] } - function validRelationshipsAndConfig() { - function validWithNumber() { + function validRelationshipsAndConfig () { + function validWithNumber () { const identity = 1 const start = 2 const end = 3 const type = 'KNOWS' - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const startNodeElementId = 'element_id_2' const endNodeElementId = 'element_id_3' @@ -336,12 +335,12 @@ describe('#unit PackStreamV5', () => { return [relStruct, expectedRel, { disableLosslessIntegers: true, useBigInt: false }] } - function validWithoutOldIdentifiersLossy() { + function validWithoutOldIdentifiersLossy () { const identity = null const start = null const end = null const type = 'KNOWS' - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const startNodeElementId = 'element_id_2' const endNodeElementId = 'element_id_3' @@ -355,12 +354,12 @@ describe('#unit PackStreamV5', () => { return [relStruct, expectedRel, { disableLosslessIntegers: true, useBigInt: false }] } - function validWithoutOldIdentifiersLossLess() { + function validWithoutOldIdentifiersLossLess () { const identity = null const start = null const end = null const type = 'KNOWS' - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const startNodeElementId = 'element_id_2' const endNodeElementId = 'element_id_3' @@ -374,12 +373,12 @@ describe('#unit PackStreamV5', () => { return [relStruct, expectedRel, { disableLosslessIntegers: false, useBigInt: false }] } - function validWithoutOldIdentifiersBigInt() { + function validWithoutOldIdentifiersBigInt () { const identity = null const start = null const end = null const type = 'KNOWS' - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const startNodeElementId = 'element_id_2' const endNodeElementId = 'element_id_3' @@ -393,12 +392,12 @@ describe('#unit PackStreamV5', () => { return [relStruct, expectedRel, { disableLosslessIntegers: true, useBigInt: true }] } - function validWithInt() { + function validWithInt () { const identity = int(1) const start = int(2) const end = int(3) const type = 'KNOWS' - const properties = { 'a': int(1), 'b': int(2) } + const properties = { a: int(1), b: int(2) } const elementId = 'element_id_1' const startNodeElementId = 'element_id_2' const endNodeElementId = 'element_id_3' @@ -412,12 +411,12 @@ describe('#unit PackStreamV5', () => { return [relStruct, expectedRel, { disableLosslessIntegers: false, useBigInt: false }] } - function validWithBigInt() { + function validWithBigInt () { const identity = BigInt(1) const start = BigInt(2) const end = BigInt(3) const type = 'KNOWS' - const properties = { 'a': BigInt(1), 'b': BigInt(2) } + const properties = { a: BigInt(1), b: BigInt(2) } const elementId = 'element_id_1' const startNodeElementId = 'element_id_2' const endNodeElementId = 'element_id_3' @@ -441,18 +440,18 @@ describe('#unit PackStreamV5', () => { ] } - function invalidRelationshipsConfig() { + function invalidRelationshipsConfig () { return [ - [new Structure(0x52, [1, 2, 3, 'rel', { 'a': 1, 'b': 2 }, 'elementId', 'startNodeId'])], - [new Structure(0x52, [1, 2, 3, 'rel', { 'a': 1, 'b': 2 }, 'elementId', 'startNodeId', 'endNodeId', 'myId'])], + [new Structure(0x52, [1, 2, 3, 'rel', { a: 1, b: 2 }, 'elementId', 'startNodeId'])], + [new Structure(0x52, [1, 2, 3, 'rel', { a: 1, b: 2 }, 'elementId', 'startNodeId', 'endNodeId', 'myId'])] ] } - function validUnboundRelationshipsAndConfig() { - function validWithNumber() { + function validUnboundRelationshipsAndConfig () { + function validWithNumber () { const identity = 1 const type = 'DOESNT_KNOW' - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const expectedUnboundRel = new UnboundRelationship(identity, type, properties, elementId) const struct = new Structure(0x72, [ @@ -461,10 +460,10 @@ describe('#unit PackStreamV5', () => { return [struct, expectedUnboundRel, { disableLosslessIntegers: true, useBigInt: false }] } - function validWithoutOldIdentifiersLossy() { + function validWithoutOldIdentifiersLossy () { const identity = null const type = 'DOESNT_KNOW' - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const expectedUnboundRel = new UnboundRelationship(-1, type, properties, elementId) const struct = new Structure(0x72, [ @@ -473,10 +472,10 @@ describe('#unit PackStreamV5', () => { return [struct, expectedUnboundRel, { disableLosslessIntegers: true, useBigInt: false }] } - function validWithoutOldIdentifiersLossless() { + function validWithoutOldIdentifiersLossless () { const identity = null const type = 'DOESNT_KNOW' - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const expectedUnboundRel = new UnboundRelationship(int(-1), type, properties, elementId) const struct = new Structure(0x72, [ @@ -485,10 +484,10 @@ describe('#unit PackStreamV5', () => { return [struct, expectedUnboundRel, { disableLosslessIntegers: false, useBigInt: false }] } - function validWithoutOldIdentifiersBigInt() { + function validWithoutOldIdentifiersBigInt () { const identity = null const type = 'DOESNT_KNOW' - const properties = { 'a': 1, 'b': 2 } + const properties = { a: 1, b: 2 } const elementId = 'element_id_1' const expectedUnboundRel = new UnboundRelationship(BigInt(-1), type, properties, elementId) const struct = new Structure(0x72, [ @@ -497,10 +496,10 @@ describe('#unit PackStreamV5', () => { return [struct, expectedUnboundRel, { disableLosslessIntegers: false, useBigInt: true }] } - function validWithInt() { + function validWithInt () { const identity = int(1) const type = 'DOESNT_KNOW' - const properties = { 'a': int(1), 'b': int(2) } + const properties = { a: int(1), b: int(2) } const elementId = 'element_id_1' const expectedUnboundRel = new UnboundRelationship(identity, type, properties, elementId) const struct = new Structure(0x72, [ @@ -509,10 +508,10 @@ describe('#unit PackStreamV5', () => { return [struct, expectedUnboundRel, { disableLosslessIntegers: false, useBigInt: false }] } - function validWithBigInt() { + function validWithBigInt () { const identity = BigInt(1) const type = 'DOESNT_KNOW' - const properties = { 'a': BigInt(1), 'b': BigInt(2) } + const properties = { a: BigInt(1), b: BigInt(2) } const elementId = 'element_id_1' const expectedUnboundRel = new UnboundRelationship(identity, type, properties, elementId) const struct = new Structure(0x72, [ @@ -531,15 +530,15 @@ describe('#unit PackStreamV5', () => { ] } - function invalidUnboundRelationshipsConfig() { + function invalidUnboundRelationshipsConfig () { return [ - [new Structure(0x72, [1, 'DOESNT_KNOW', { 'a': 1, 'b': 2 }])], - [new Structure(0x72, [1, 'DOESNT_KNOW', { 'a': 1, 'b': 2 }, 'elementId', 'myId'])], + [new Structure(0x72, [1, 'DOESNT_KNOW', { a: 1, b: 2 }])], + [new Structure(0x72, [1, 'DOESNT_KNOW', { a: 1, b: 2 }, 'elementId', 'myId'])] ] } }) -function packAndUnpack( +function packAndUnpack ( val, { bufferSize = 128, disableLosslessIntegers = false, useBigInt = false } = {} ) { diff --git a/packages/bolt-connection/test/pool/pool.test.js b/packages/bolt-connection/test/pool/pool.test.js index 90b627ee7..75ab484c0 100644 --- a/packages/bolt-connection/test/pool/pool.test.js +++ b/packages/bolt-connection/test/pool/pool.test.js @@ -182,9 +182,9 @@ describe('#unit Pool', () => { // When const r00 = await pool.acquire(address1) const r01 = await pool.acquire(address1) - const r10 = await pool.acquire(address2) - const r11 = await pool.acquire(address2) - const r12 = await pool.acquire(address2) + await pool.acquire(address2) + await pool.acquire(address2) + await pool.acquire(address2) expect(pool.activeResourceCount(address1)).toEqual(2) expect(pool.activeResourceCount(address2)).toEqual(3) @@ -371,7 +371,7 @@ describe('#unit Pool', () => { pool.acquire(address2), pool.acquire(address3) ] - const values = await Promise.all(acquiredResources) + await Promise.all(acquiredResources) expect(pool.has(address1)).toBeTruthy() expect(pool.has(address2)).toBeTruthy() @@ -408,7 +408,7 @@ describe('#unit Pool', () => { pool.acquire(address2), pool.acquire(address3) ] - const values = await Promise.all(acquiredResources) + await Promise.all(acquiredResources) expect(pool.has(address1)).toBeTruthy() expect(pool.has(address2)).toBeTruthy() @@ -457,8 +457,8 @@ describe('#unit Pool', () => { Promise.resolve(new Resource(server, 42, release)) }) - const r1 = await pool.acquire(existingAddress) - const r0 = await pool.acquire(existingAddress) + await pool.acquire(existingAddress) + await pool.acquire(existingAddress) expect(pool.has(existingAddress)).toBeTruthy() expect(pool.has(absentAddress)).toBeFalsy() @@ -568,7 +568,7 @@ describe('#unit Pool', () => { config: new PoolConfig(2, 5000) }) - const r0 = await pool.acquire(address) + await pool.acquire(address) const r1 = await pool.acquire(address) setTimeout(() => { @@ -899,8 +899,8 @@ describe('#unit Pool', () => { } catch (e) { expect(e).toEqual( newError( - `Connection acquisition timed out in ${acquisitionTimeout} ms. ` - + 'Pool status: Active conn count = 0, Idle conn count = 0.' + `Connection acquisition timed out in ${acquisitionTimeout} ms. ` + + 'Pool status: Active conn count = 0, Idle conn count = 0.' ) ) @@ -932,7 +932,7 @@ function expectNoIdleResources (pool, address) { function idleResources (pool, address) { if (pool.has(address)) { return pool._pools[address.asKey()].length - } + } return undefined } diff --git a/packages/bolt-connection/test/rediscovery/rediscovery.test.js b/packages/bolt-connection/test/rediscovery/rediscovery.test.js index 5a2417694..60365be72 100644 --- a/packages/bolt-connection/test/rediscovery/rediscovery.test.js +++ b/packages/bolt-connection/test/rediscovery/rediscovery.test.js @@ -28,9 +28,8 @@ const { serverAddress: { ServerAddress } } = internal -const { PROTOCOL_ERROR, SERVICE_UNAVAILABLE } = error +const { PROTOCOL_ERROR } = error -const PROCEDURE_NOT_FOUND_CODE = 'Neo.ClientError.Procedure.ProcedureNotFound' const DATABASE_NOT_FOUND_CODE = 'Neo.ClientError.Database.DatabaseNotFound' describe('#unit Rediscovery', () => { From 7d3df8e98fe78856a7789b55cde5a6bc56ab58af Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Wed, 20 Apr 2022 11:33:14 +0200 Subject: [PATCH 06/13] Applying linter to packages/neo4j-driver-lite/src --- packages/neo4j-driver-lite/src/index.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/neo4j-driver-lite/src/index.ts b/packages/neo4j-driver-lite/src/index.ts index 34adfab78..e961d2108 100644 --- a/packages/neo4j-driver-lite/src/index.ts +++ b/packages/neo4j-driver-lite/src/index.ts @@ -87,7 +87,7 @@ type ConfiguredCustomResolver = internal.resolver.ConfiguredCustomResolver const { READ, WRITE } = coreDriver const { - util: { ENCRYPTION_ON, ENCRYPTION_OFF, assertString, isEmptyObjectOrNull }, + util: { ENCRYPTION_ON, assertString, isEmptyObjectOrNull }, serverAddress: { ServerAddress }, urlUtil } = internal @@ -259,7 +259,7 @@ function driver ( routing = true break default: - throw new Error(`Unknown scheme: ${parsedUrl.scheme}`) + throw new Error(`Unknown scheme: ${parsedUrl.scheme ?? 'null'}`) } // Encryption enabled on URL, propagate trust to the config. @@ -275,11 +275,11 @@ function driver ( } // Sanitize authority token. Nicer error from server when a scheme is set. - authToken = authToken || {} - authToken.scheme = authToken.scheme || 'none' + authToken = authToken ?? {} + authToken.scheme = authToken.scheme ?? 'none' // Use default user agent or user agent specified by user. - config.userAgent = config.userAgent || USER_AGENT + config.userAgent = config.userAgent ?? USER_AGENT const address = ServerAddress.fromUrl(parsedUrl.hostAndPort) const meta = { @@ -290,7 +290,7 @@ function driver ( return new Driver(meta, config, createConnectionProviderFunction()) - function createConnectionProviderFunction () { + function createConnectionProviderFunction (): (id: number, config: Config, log: Logger, hostNameResolver: ConfiguredCustomResolver) => ConnectionProvider { if (routing) { return ( id: number, @@ -500,6 +500,6 @@ export type { TrustStrategy, SessionMode, ResultObserver, - NotificationPosition, + NotificationPosition } export default forExport From 3afb442b864fd976e43d86b4ab32cccaa7e26b25 Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Wed, 20 Apr 2022 11:37:44 +0200 Subject: [PATCH 07/13] Applying linter to packages/neo4j-driver-lite/test --- .../neo4j-driver-lite/test/integration/config.ts | 14 +++++--------- packages/neo4j-driver-lite/test/unit/index.test.ts | 12 ++++++------ 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/packages/neo4j-driver-lite/test/integration/config.ts b/packages/neo4j-driver-lite/test/integration/config.ts index db5a1c6a2..ea7ca6f15 100644 --- a/packages/neo4j-driver-lite/test/integration/config.ts +++ b/packages/neo4j-driver-lite/test/integration/config.ts @@ -17,17 +17,13 @@ * limitations under the License. */ -// @ts-ignore const env = process.env -const username = env.TEST_NEO4J_USER || 'neo4j' -const password = env.TEST_NEO4J_PASS || 'password' -const hostname = env.TEST_NEO4J_HOST || 'localhost' -const scheme = env.TEST_NEO4J_SCHEME || 'bolt' -const cluster = - env.TEST_NEO4J_IS_CLUSTER !== undefined - ? env.TEST_NEO4J_IS_CLUSTER === '1' - : false +const username = env.TEST_NEO4J_USER ?? 'neo4j' +const password = env.TEST_NEO4J_PASS ?? 'password' +const hostname = env.TEST_NEO4J_HOST ?? 'localhost' +const scheme = env.TEST_NEO4J_SCHEME ?? 'bolt' +const cluster = env.TEST_NEO4J_IS_CLUSTER === '1' const testNonClusterSafe = cluster ? test.skip.bind(test) : test diff --git a/packages/neo4j-driver-lite/test/unit/index.test.ts b/packages/neo4j-driver-lite/test/unit/index.test.ts index 8f25ed7fe..3d19fe85c 100644 --- a/packages/neo4j-driver-lite/test/unit/index.test.ts +++ b/packages/neo4j-driver-lite/test/unit/index.test.ts @@ -217,12 +217,12 @@ describe('index', () => { mode: 'READ', reactive: false, connectionProvider: { - acquireConnection: () => Promise.reject(Error('something wrong')), - close: () => Promise.resolve(), - supportsMultiDb: () => Promise.resolve(true), - supportsTransactionConfig: () => Promise.resolve(true), - supportsUserImpersonation: () => Promise.resolve(true), - verifyConnectivityAndGetServerInfo: () => Promise.resolve(new ServerInfo({})) + acquireConnection: async () => { throw Error('something wrong') }, + close: async () => {}, + supportsMultiDb: async () => true, + supportsTransactionConfig: async () => true, + supportsUserImpersonation: async () => true, + verifyConnectivityAndGetServerInfo: async () => new ServerInfo({}) } }) expect(session).toBeDefined() From 6d5c2b291621dcb0a81368f609e4ebea99e223ae Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Wed, 20 Apr 2022 11:44:42 +0200 Subject: [PATCH 08/13] Applying linter to packages/neo4j-driver/src --- packages/neo4j-driver/src/index.js | 3 +- .../src/internal/retry-logic-rx.js | 3 +- .../src/internal/server-version.js | 5 ++- packages/neo4j-driver/src/result-rx.js | 9 ++++++ packages/neo4j-driver/src/session-rx.js | 6 ++-- .../src/transaction-managed-rx.js | 12 ++++--- packages/neo4j-driver/src/transaction-rx.js | 3 +- packages/neo4j-driver/types/driver.d.ts | 11 ++----- packages/neo4j-driver/types/index.d.ts | 10 +++--- packages/neo4j-driver/types/query-runner.d.ts | 2 +- packages/neo4j-driver/types/result-rx.d.ts | 12 +++---- packages/neo4j-driver/types/session-rx.d.ts | 32 +++++++++---------- .../types/transaction-managed-rx.d.ts | 17 +++++----- .../neo4j-driver/types/transaction-rx.d.ts | 12 +++---- 14 files changed, 70 insertions(+), 67 deletions(-) diff --git a/packages/neo4j-driver/src/index.js b/packages/neo4j-driver/src/index.js index d63fd87cc..71c457b20 100644 --- a/packages/neo4j-driver/src/index.js +++ b/packages/neo4j-driver/src/index.js @@ -52,7 +52,6 @@ import { Record, ResultSummary, Result, - ConnectionProvider, auth } from 'neo4j-driver-core' import { @@ -61,7 +60,7 @@ import { } from 'neo4j-driver-bolt-connection' const { - util: { ENCRYPTION_ON, ENCRYPTION_OFF, assertString, isEmptyObjectOrNull }, + util: { ENCRYPTION_ON, assertString, isEmptyObjectOrNull }, serverAddress: { ServerAddress }, urlUtil } = internal diff --git a/packages/neo4j-driver/src/internal/retry-logic-rx.js b/packages/neo4j-driver/src/internal/retry-logic-rx.js index 2ff7968e2..2361e23ad 100644 --- a/packages/neo4j-driver/src/internal/retry-logic-rx.js +++ b/packages/neo4j-driver/src/internal/retry-logic-rx.js @@ -18,6 +18,7 @@ */ import { newError, error, internal, isRetriableError } from 'neo4j-driver-core' +// eslint-disable-next-line no-unused-vars import { Observable, throwError, of } from 'rxjs' import { retryWhen, flatMap, delay } from 'rxjs/operators' @@ -28,7 +29,7 @@ const { } } = internal -const { SERVICE_UNAVAILABLE, SESSION_EXPIRED } = error +const { SERVICE_UNAVAILABLE } = error const DEFAULT_MAX_RETRY_TIME_MS = 30 * 1000 // 30 seconds const DEFAULT_INITIAL_RETRY_DELAY_MS = 1000 // 1 seconds const DEFAULT_RETRY_DELAY_MULTIPLIER = 2.0 diff --git a/packages/neo4j-driver/src/internal/server-version.js b/packages/neo4j-driver/src/internal/server-version.js index 7a20aa702..5019faea4 100644 --- a/packages/neo4j-driver/src/internal/server-version.js +++ b/packages/neo4j-driver/src/internal/server-version.js @@ -23,9 +23,8 @@ const { util: { assertString } } = internal -const SERVER_VERSION_REGEX = new RegExp( - '^(Neo4j/)?(\\d+)\\.(\\d+)(?:\\.)?(\\d*)(\\.|-|\\+)?([0-9A-Za-z-.]*)?$' -) +const SERVER_VERSION_REGEX = /^(Neo4j\/)?(\d+)\.(\d+)(?:\.)?(\d*)(\.|-|\+)?([0-9A-Za-z-.]*)?$/ + const NEO4J_IN_DEV_VERSION_STRING = 'Neo4j/dev' class ServerVersion { diff --git a/packages/neo4j-driver/src/result-rx.js b/packages/neo4j-driver/src/result-rx.js index 9f28982c3..4f77e96b1 100644 --- a/packages/neo4j-driver/src/result-rx.js +++ b/packages/neo4j-driver/src/result-rx.js @@ -16,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable-next-line no-unused-vars */ import { newError, Record, ResultSummary } from 'neo4j-driver-core' import { Observable, Subject, ReplaySubject, from } from 'rxjs' import { flatMap, publishReplay, refCount } from 'rxjs/operators' @@ -264,6 +265,10 @@ class StreamControl { this._pushing = pushing } + get pushing () { + return this._pushing + } + async resume () { const wasPaused = this._paused this._paused = false @@ -280,4 +285,8 @@ class StreamControl { set pusher (push) { this._push = push } + + get pusher () { + return this._push + } } diff --git a/packages/neo4j-driver/src/session-rx.js b/packages/neo4j-driver/src/session-rx.js index aed6315ec..f31c09c03 100644 --- a/packages/neo4j-driver/src/session-rx.js +++ b/packages/neo4j-driver/src/session-rx.js @@ -19,6 +19,7 @@ import { defer, Observable, throwError } from 'rxjs' import { flatMap, catchError, concat } from 'rxjs/operators' import RxResult from './result-rx' +// eslint-disable-next-line no-unused-vars import { Session, internal } from 'neo4j-driver-core' import RxTransaction from './transaction-rx' import RxManagedTransaction from './transaction-managed-rx' @@ -107,7 +108,6 @@ export default class RxSession { return this._runTransaction(ACCESS_MODE_WRITE, work, transactionConfig) } - /** * Executes the provided unit of work in a {@link READ} reactive transaction which is created with the provided * transaction configuration. @@ -116,7 +116,7 @@ export default class RxSession { * @param {TransactionConfig} transactionConfig - Configuration for the enclosing transaction created by the driver. * @returns {Observable} - A reactive stream returned by the unit of work. */ - executeRead (work, transactionConfig) { + executeRead (work, transactionConfig) { return this._executeInTransaction(ACCESS_MODE_READ, work, transactionConfig) } @@ -229,7 +229,7 @@ export default class RxSession { } return this._retryLogic.retry( - this._beginTransaction(accessMode, transactionConfig).pipe( + this._beginTransaction(accessMode, txConfig).pipe( flatMap(txc => defer(() => { try { diff --git a/packages/neo4j-driver/src/transaction-managed-rx.js b/packages/neo4j-driver/src/transaction-managed-rx.js index 5e9a7a24a..a50737dba 100644 --- a/packages/neo4j-driver/src/transaction-managed-rx.js +++ b/packages/neo4j-driver/src/transaction-managed-rx.js @@ -16,19 +16,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +// eslint-disable-next-line no-unused-vars import RxResult from './result-rx' +// eslint-disable-next-line no-unused-vars import RxTransaction from './transaction-rx' /** * Represents a rx transaction that is managed by the transaction executor. - * + * * @public */ class RxManagedTransaction { /** * @private */ - constructor({ run }) { + constructor ({ run }) { this._run = run } @@ -51,9 +53,9 @@ class RxManagedTransaction { * @param {Object} parameters - Parameter values to use in query execution. * @returns {RxResult} - A reactive result */ - run (query, parameters) { - return this._run(query, parameters) - } + run (query, parameters) { + return this._run(query, parameters) + } } export default RxManagedTransaction diff --git a/packages/neo4j-driver/src/transaction-rx.js b/packages/neo4j-driver/src/transaction-rx.js index e41621792..bc86ebb8b 100644 --- a/packages/neo4j-driver/src/transaction-rx.js +++ b/packages/neo4j-driver/src/transaction-rx.js @@ -18,6 +18,7 @@ */ import { Observable } from 'rxjs' import RxResult from './result-rx' +// eslint-disable-next-line no-unused-vars import Transaction from 'neo4j-driver-core' /** @@ -94,7 +95,7 @@ export default class RxTransaction { * Check if this transaction is active, which means commit and rollback did not happen. * @return {boolean} `true` when not committed and not rolled back, `false` otherwise. */ - isOpen() { + isOpen () { return this._txc.isOpen() } diff --git a/packages/neo4j-driver/types/driver.d.ts b/packages/neo4j-driver/types/driver.d.ts index 15cd88ebf..ca6cc2094 100644 --- a/packages/neo4j-driver/types/driver.d.ts +++ b/packages/neo4j-driver/types/driver.d.ts @@ -19,8 +19,6 @@ import RxSession from './session-rx' import { - ServerInfo, - Session, Driver as CoreDriver, types } from 'neo4j-driver-core' @@ -36,17 +34,12 @@ declare const READ: SessionMode declare const WRITE: SessionMode declare interface Driver extends CoreDriver { - rxSession({ - defaultAccessMode, - bookmarks, - database, - fetchSize - }?: { + rxSession: (sessionParams?: { defaultAccessMode?: SessionMode bookmarks?: string | string[] fetchSize?: number database?: string - }): RxSession + }) => RxSession } export { diff --git a/packages/neo4j-driver/types/index.d.ts b/packages/neo4j-driver/types/index.d.ts index 0835c3c2c..9fae6c71d 100644 --- a/packages/neo4j-driver/types/index.d.ts +++ b/packages/neo4j-driver/types/index.d.ts @@ -94,7 +94,7 @@ declare const auth: { ) => AuthToken } -declare function driver( +declare function driver ( url: string, authToken?: AuthToken, config?: Config @@ -119,7 +119,7 @@ declare const types: { Integer: typeof Integer RxSession: RxSession RxTransaction: RxTransaction - RxManagedTransaction: RxManagedTransaction, + RxManagedTransaction: RxManagedTransaction RxResult: RxResult } @@ -193,8 +193,8 @@ declare const forExport: { ServerInfo: ServerInfo NotificationPosition: NotificationPosition Session: Session - Transaction: Transaction, - ManagedTransaction: ManagedTransaction, + Transaction: Transaction + ManagedTransaction: ManagedTransaction Point: Point isPoint: typeof isPoint Duration: Duration @@ -205,7 +205,7 @@ declare const forExport: { DateTime: DateTime RxSession: RxSession RxTransaction: RxTransaction - RxManagedTransaction: RxManagedTransaction, + RxManagedTransaction: RxManagedTransaction RxResult: RxResult ConnectionProvider: ConnectionProvider isDuration: typeof isDuration diff --git a/packages/neo4j-driver/types/query-runner.d.ts b/packages/neo4j-driver/types/query-runner.d.ts index 8b673aa5f..ac3db5245 100644 --- a/packages/neo4j-driver/types/query-runner.d.ts +++ b/packages/neo4j-driver/types/query-runner.d.ts @@ -21,7 +21,7 @@ import { Result, types } from 'neo4j-driver-core' declare type Parameters = types.Parameters declare interface QueryRunner { - run(query: string, parameters?: Parameters): Result + run: (query: string, parameters?: Parameters) => Result } export { Parameters } diff --git a/packages/neo4j-driver/types/result-rx.d.ts b/packages/neo4j-driver/types/result-rx.d.ts index 0d7136326..25f81c0c0 100644 --- a/packages/neo4j-driver/types/result-rx.d.ts +++ b/packages/neo4j-driver/types/result-rx.d.ts @@ -20,17 +20,17 @@ import { Observable } from 'rxjs' import { Record, ResultSummary } from 'neo4j-driver-core' declare interface RxResult { - keys(): Observable + keys: () => Observable - records(): Observable + records: () => Observable - consume(): Observable + consume: () => Observable - pause(): void + pause: () => void - resume(): Promise + resume: () => Promise - push(): Promise + push: () => Promise } export default RxResult diff --git a/packages/neo4j-driver/types/session-rx.d.ts b/packages/neo4j-driver/types/session-rx.d.ts index f0137b9ea..72c71a0d3 100644 --- a/packages/neo4j-driver/types/session-rx.d.ts +++ b/packages/neo4j-driver/types/session-rx.d.ts @@ -25,43 +25,43 @@ import { Observable } from 'rxjs' declare type RxTransactionWork = (tx: RxTransaction) => Observable declare interface RxSession { - run( + run: ( query: string, parameters?: Parameters, config?: TransactionConfig - ): RxResult + ) => RxResult - beginTransaction(config?: TransactionConfig): Observable + beginTransaction: (config?: TransactionConfig) => Observable - lastBookmarks(): string[] - lastBookmark(): string[] + lastBookmarks: () => string[] + lastBookmark: () => string[] /** - * @deprecated This method will be removed in version 6.0. Please, use {@link RxSession#executeRead} instead. + * @deprecated This method will be removed in version 6.0. Please, use {@link RxSession#executeRead} instead. */ - readTransaction( + readTransaction: ( work: RxTransactionWork, config?: TransactionConfig - ): Observable + ) => Observable /** - * @deprecated This method will be removed in version 6.0. Please, use {@link RxSession#executeWrite} instead. + * @deprecated This method will be removed in version 6.0. Please, use {@link RxSession#executeWrite} instead. */ - writeTransaction( + writeTransaction: ( work: RxTransactionWork, config?: TransactionConfig - ): Observable + ) => Observable - executeRead( + executeRead: ( work: RxTransactionWork, config?: TransactionConfig - ): Observable + ) => Observable - executeWrite( + executeWrite: ( work: RxTransactionWork, config?: TransactionConfig - ): Observable + ) => Observable - close(): Observable + close: () => Observable } export default RxSession diff --git a/packages/neo4j-driver/types/transaction-managed-rx.d.ts b/packages/neo4j-driver/types/transaction-managed-rx.d.ts index 4e2a37f21..a6722395e 100644 --- a/packages/neo4j-driver/types/transaction-managed-rx.d.ts +++ b/packages/neo4j-driver/types/transaction-managed-rx.d.ts @@ -16,12 +16,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - import { Parameters } from './query-runner' - import RxResult from './result-rx' - - declare interface RxManagedTransaction { - run(query: string, parameters?: Parameters): RxResult - } - - export default RxManagedTransaction - \ No newline at end of file +import { Parameters } from './query-runner' +import RxResult from './result-rx' + +declare interface RxManagedTransaction { + run: (query: string, parameters?: Parameters) => RxResult +} + +export default RxManagedTransaction diff --git a/packages/neo4j-driver/types/transaction-rx.d.ts b/packages/neo4j-driver/types/transaction-rx.d.ts index 1b0ff4be1..379b79900 100644 --- a/packages/neo4j-driver/types/transaction-rx.d.ts +++ b/packages/neo4j-driver/types/transaction-rx.d.ts @@ -21,15 +21,15 @@ import { Parameters } from './query-runner' import RxResult from './result-rx' declare interface RxTransaction { - run(query: string, parameters?: Parameters): RxResult - - isOpen(): boolean + run: (query: string, parameters?: Parameters) => RxResult - commit(): Observable + isOpen: () => boolean - rollback(): Observable + commit: () => Observable - close(): Observable + rollback: () => Observable + + close: () => Observable } export default RxTransaction From ba832ae9629e102830088d6dfcb2e5eb5018e59f Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Wed, 20 Apr 2022 12:15:39 +0200 Subject: [PATCH 09/13] Small fixes --- packages/core/src/internal/bookmarks.ts | 2 +- .../test/types/result-summary.test.ts | 42 +++++++++---------- packages/neo4j-driver/tsconfig.json | 2 +- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/packages/core/src/internal/bookmarks.ts b/packages/core/src/internal/bookmarks.ts index 21885aad3..11524191a 100644 --- a/packages/core/src/internal/bookmarks.ts +++ b/packages/core/src/internal/bookmarks.ts @@ -81,7 +81,7 @@ const EMPTY_BOOKMARK = new Bookmarks(null) function asStringArray ( value?: string | string[] | string[] | null ): string[] { - if (value == null) { + if (value == null || value === '') { return [] } diff --git a/packages/neo4j-driver/test/types/result-summary.test.ts b/packages/neo4j-driver/test/types/result-summary.test.ts index 1df845d1a..35252be05 100644 --- a/packages/neo4j-driver/test/types/result-summary.test.ts +++ b/packages/neo4j-driver/test/types/result-summary.test.ts @@ -16,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ import { Integer, @@ -46,39 +47,39 @@ const systemUpdates: number = counters.systemUpdates() const updates: { [key: string]: number } = counters.updates() const plan: Plan | false = sum1.plan -const planOperatorType: string | false = plan ? plan.operatorType : false -const planIdentifiers: string[] | false = plan ? plan.identifiers : false -const planArguments: { [key: string]: string } | false = plan +const planOperatorType: string | false = plan !== false ? plan.operatorType : false +const planIdentifiers: string[] | false = plan !== false ? plan.identifiers : false +const planArguments: { [key: string]: string } | false = plan !== false ? plan.arguments : false -const planChildren: Plan[] | false = plan ? plan.children : false +const planChildren: Plan[] | false = plan !== false ? plan.children : false const profile: ProfiledPlan | false = sum1.profile -const profileOperatorType: string | false = profile +const profileOperatorType: string | false = profile !== false ? profile.operatorType : false -const profileIdentifiers: string[] | false = profile +const profileIdentifiers: string[] | false = profile !== false ? profile.identifiers : false -const profileArguments: { [key: string]: string } | false = profile +const profileArguments: { [key: string]: string } | false = profile !== false ? profile.arguments : false -const profileDbHits: number | false = profile ? profile.dbHits : false -const profileRows: number | false = profile ? profile.rows : false -const hasPageCacheStats: boolean | false = profile +const profileDbHits: number | false = profile !== false ? profile.dbHits : false +const profileRows: number | false = profile !== false ? profile.rows : false +const hasPageCacheStats: boolean | false = profile !== false ? profile.hasPageCacheStats() : false -const profilePageCacheMisses: number | false = profile +const profilePageCacheMisses: number | false = profile !== false ? profile.pageCacheMisses : false -const profilePageCacheHits: number | false = profile +const profilePageCacheHits: number | false = profile !== false ? profile.pageCacheHits : false -const profilePageCacheHitRatio: number | false = profile +const profilePageCacheHitRatio: number | false = profile !== false ? profile.pageCacheHitRatio : false -const time: number | false = profile ? profile.time : false -const profileChildren: ProfiledPlan[] | false = profile +const time: number | false = profile !== false ? profile.time : false +const profileChildren: ProfiledPlan[] | false = profile !== false ? profile.children : false @@ -89,12 +90,11 @@ const title: string = notification.title const description: string = notification.description const severity: string = notification.severity const position1: NotificationPosition | {} = notification.position -const position2: NotificationPosition = ( - notification.position -) -const offset: number = position2.offset -const line: number = position2.line -const column: number = position2.column +const position2: NotificationPosition = notification.position as NotificationPosition + +const offset: number | undefined = position2.offset +const line: number | undefined = position2.line +const column: number | undefined = position2.column const server: ServerInfo = sum1.server const address: string | undefined = server.address diff --git a/packages/neo4j-driver/tsconfig.json b/packages/neo4j-driver/tsconfig.json index 35a318b36..0a15b90b3 100644 --- a/packages/neo4j-driver/tsconfig.json +++ b/packages/neo4j-driver/tsconfig.json @@ -8,5 +8,5 @@ "moduleResolution": "node", "types": [] }, - "include": ["types/**/*.ts"] + "include": ["types/**/*.ts", "test/types/**/*.ts"] } From 4d63d0e7d1a1f3b5d9fc64d3a3ad89fb44569157 Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Wed, 20 Apr 2022 12:36:45 +0200 Subject: [PATCH 10/13] Applying linter to packages/neo4j-driver/test --- packages/neo4j-driver/test/bolt-v3.test.js | 8 ++--- packages/neo4j-driver/test/driver.test.js | 13 ++------ packages/neo4j-driver/test/examples.test.js | 5 +--- .../neo4j-driver/test/internal/bolt-stub.js | 6 ++-- .../test/internal/connection-channel.test.js | 2 +- .../connection-holder-readonly.test.js | 1 - .../test/internal/connection-holder.test.js | 1 - .../test/internal/node/package.test.js | 30 +++++++++---------- .../node/routing.driver.boltkit.test.js | 4 +-- .../test/internal/temporal-util.test.js | 26 ---------------- .../test/nested-statements.test.js | 5 +--- .../neo4j-driver/test/rx/navigation.test.js | 3 ++ .../test/rx/nested-statements.test.js | 1 + packages/neo4j-driver/test/rx/session.test.js | 7 ++--- packages/neo4j-driver/test/rx/summary.test.js | 2 ++ .../neo4j-driver/test/rx/transaction.test.js | 7 ++--- packages/neo4j-driver/test/session.test.js | 21 +------------ .../neo4j-driver/test/transaction.test.js | 6 +--- .../neo4j-driver/test/types/driver.test.ts | 29 +++++++++--------- .../neo4j-driver/test/types/export.test.ts | 4 ++- .../test/types/graph-types.test.ts | 12 ++++---- .../neo4j-driver/test/types/index.test.ts | 4 ++- .../neo4j-driver/test/types/integer.test.ts | 2 ++ .../neo4j-driver/test/types/record.test.ts | 6 ++-- .../neo4j-driver/test/types/result-rx.test.ts | 12 ++++++-- .../neo4j-driver/test/types/result.test.ts | 2 ++ .../test/types/session-rx.test.ts | 13 ++++++-- .../neo4j-driver/test/types/session.test.ts | 10 ++++--- .../test/types/spatial-types.test.ts | 2 ++ .../test/types/temporal-types.test.ts | 2 ++ .../test/types/transaction-managed-rx.test.ts | 14 +++++++-- .../test/types/transaction-rx.test.ts | 14 +++++++-- .../test/types/transaction.test.ts | 6 ++-- 33 files changed, 134 insertions(+), 146 deletions(-) diff --git a/packages/neo4j-driver/test/bolt-v3.test.js b/packages/neo4j-driver/test/bolt-v3.test.js index 33d05783f..736c018db 100644 --- a/packages/neo4j-driver/test/bolt-v3.test.js +++ b/packages/neo4j-driver/test/bolt-v3.test.js @@ -92,8 +92,8 @@ describe('#integration Bolt V3 API', () => { } catch (e) { // ClientError on 4.1 and later if ( - e.code != 'Neo.ClientError.Transaction.TransactionTimedOut' && - e.code != 'Neo.TransientError.Transaction.LockClientStopped' + e.code !== 'Neo.ClientError.Transaction.TransactionTimedOut' && + e.code !== 'Neo.TransientError.Transaction.LockClientStopped' ) { fail('Expected transaction timeout error but got: ' + e.code) } @@ -215,8 +215,8 @@ describe('#integration Bolt V3 API', () => { } catch (e) { // ClientError on 4.1 and later if ( - e.code != 'Neo.ClientError.Transaction.TransactionTimedOut' && - e.code != 'Neo.TransientError.Transaction.LockClientStopped' + e.code !== 'Neo.ClientError.Transaction.TransactionTimedOut' && + e.code !== 'Neo.TransientError.Transaction.LockClientStopped' ) { fail('Expected transaction timeout error but got: ' + e.code) } diff --git a/packages/neo4j-driver/test/driver.test.js b/packages/neo4j-driver/test/driver.test.js index cb1d20ce7..f4b7abaa5 100644 --- a/packages/neo4j-driver/test/driver.test.js +++ b/packages/neo4j-driver/test/driver.test.js @@ -192,8 +192,8 @@ describe('#integration driver', () => { Promise.all([result1, result2]).then(results => { driver.close() beginTxWithoutCommit(driver).catch(() => { - var pool = driver._connectionProvider._connectionPool - var serverKey = Object.keys(pool._activeResourceCounts)[0] + const pool = driver._connectionProvider._connectionPool + const serverKey = Object.keys(pool._activeResourceCounts)[0] expect(pool._activeResourceCounts[serverKey]).toEqual(2) expect(serverKey in pool._pools).toBeFalsy() expect( @@ -654,15 +654,6 @@ describe('#integration driver', () => { .then(() => done()) } - /** - * Starts new transaction to force new network connection. - * @param {Driver} driver - the driver to use. - */ - function startNewTransaction (driver) { - const session = driver.session() - expect(session.beginTransaction()).toBeDefined() - } - function wrongCredentials () { return neo4j.auth.basic('neo4j', 'who would use such a password') } diff --git a/packages/neo4j-driver/test/examples.test.js b/packages/neo4j-driver/test/examples.test.js index a2e1e39c0..27b4d420c 100644 --- a/packages/neo4j-driver/test/examples.test.js +++ b/packages/neo4j-driver/test/examples.test.js @@ -17,9 +17,8 @@ * limitations under the License. */ -import neo4j, { session } from '../src' +import neo4j from '../src' import sharedNeo4j from './internal/shared-neo4j' -import { ServerVersion, VERSION_4_0_0 } from '../src/internal/server-version' import { bufferCount, map, @@ -38,8 +37,6 @@ import { Notification } from 'rxjs' */ describe('#integration examples', () => { - const originalConsole = console - let driverGlobal let protocolVersion let edition diff --git a/packages/neo4j-driver/test/internal/bolt-stub.js b/packages/neo4j-driver/test/internal/bolt-stub.js index a06c22f93..a6067aa0a 100644 --- a/packages/neo4j-driver/test/internal/bolt-stub.js +++ b/packages/neo4j-driver/test/internal/bolt-stub.js @@ -90,7 +90,7 @@ class SupportedBoltStub extends UnsupportedBoltStub { let timedOut = false const timeoutId = setTimeout(() => { timedOut = true - reject(`unable to connect to localhost:${port}`) + reject(new Error(`unable to connect to localhost:${port}`)) }, 15000) const tryConnect = () => { @@ -136,7 +136,7 @@ class StubServer { let timedOut = false const timeoutId = setTimeout(() => { timedOut = true - reject('timed out waiting for the stub server to exit') + reject(new Error('timed out waiting for the stub server to exit')) }, 5000) const checkStatus = () => { @@ -147,7 +147,7 @@ class StubServer { if (exitStatus.code === 0) { resolve() } else { - reject(`stub server exited with code: ${exitStatus.code}`) + reject(new Error(`stub server exited with code: ${exitStatus.code}`)) } } else { if (!timedOut) { diff --git a/packages/neo4j-driver/test/internal/connection-channel.test.js b/packages/neo4j-driver/test/internal/connection-channel.test.js index 69d661e1e..ccee03fc0 100644 --- a/packages/neo4j-driver/test/internal/connection-channel.test.js +++ b/packages/neo4j-driver/test/internal/connection-channel.test.js @@ -18,7 +18,7 @@ */ import DummyChannel from './dummy-channel' -import ChannelConnection, { +import { createChannelConnection } from '../../../bolt-connection/lib/connection/connection-channel' import { Packer } from '../../../bolt-connection/lib/packstream/packstream-v1' diff --git a/packages/neo4j-driver/test/internal/connection-holder-readonly.test.js b/packages/neo4j-driver/test/internal/connection-holder-readonly.test.js index c71603643..9484831ec 100644 --- a/packages/neo4j-driver/test/internal/connection-holder-readonly.test.js +++ b/packages/neo4j-driver/test/internal/connection-holder-readonly.test.js @@ -20,7 +20,6 @@ import SingleConnectionProvider from '../../../bolt-connection/lib/connection-provider/connection-provider-single' import { READ, WRITE } from '../../src/driver' import FakeConnection from './fake-connection' -import Connection from '../../../bolt-connection/lib/connection/connection' import { internal } from 'neo4j-driver-core' const { diff --git a/packages/neo4j-driver/test/internal/connection-holder.test.js b/packages/neo4j-driver/test/internal/connection-holder.test.js index f9ef9484e..db82ee64c 100644 --- a/packages/neo4j-driver/test/internal/connection-holder.test.js +++ b/packages/neo4j-driver/test/internal/connection-holder.test.js @@ -20,7 +20,6 @@ import SingleConnectionProvider from '../../../bolt-connection/lib/connection-provider/connection-provider-single' import { READ, WRITE } from '../../src/driver' import FakeConnection from './fake-connection' -import Connection from '../../../bolt-connection/lib/connection/connection' import { internal } from 'neo4j-driver-core' const { diff --git a/packages/neo4j-driver/test/internal/node/package.test.js b/packages/neo4j-driver/test/internal/node/package.test.js index 3ed99438d..c88adda3f 100644 --- a/packages/neo4j-driver/test/internal/node/package.test.js +++ b/packages/neo4j-driver/test/internal/node/package.test.js @@ -17,13 +17,13 @@ * limitations under the License. */ -var path = require('path') -var fs = require('fs') -var webpack = require('webpack') -var sharedNeo4j = require('../shared-neo4j').default +const path = require('path') +const fs = require('fs') +const webpack = require('webpack') +const sharedNeo4j = require('../shared-neo4j').default describe('Package', function () { - var driver + let driver afterAll(async () => { if (driver) { @@ -32,7 +32,7 @@ describe('Package', function () { }) it('should work in NodeJS', function (done) { - var neo4j + let neo4j try { neo4j = require(sandboxPath('node_modules', 'neo4j-driver', 'lib')) @@ -44,7 +44,7 @@ describe('Package', function () { 'bolt://localhost', neo4j.auth.basic(sharedNeo4j.username, sharedNeo4j.password) ) - var session = driver.session() + const session = driver.session() session .run('RETURN 1 AS answer') .then(function (result) { @@ -71,10 +71,10 @@ describe('Package', function () { // └── index.js /* eslint-enable no-irregular-whitespace */ - var projectDir = sandboxPath() - var srcDir = path.join(projectDir, 'src') - var distDir = path.join(projectDir, 'dist') - var indexJsFile = path.join(srcDir, 'index.js') + const projectDir = sandboxPath() + const srcDir = path.join(projectDir, 'src') + const distDir = path.join(projectDir, 'dist') + const indexJsFile = path.join(srcDir, 'index.js') // create src directory fs.mkdirSync(srcDir) @@ -82,7 +82,7 @@ describe('Package', function () { fs.writeFileSync(indexJsFile, 'require("neo4j-driver");\n') // configuration for Webpack - var webpackOptions = { + const webpackOptions = { mode: 'development', context: projectDir, output: { @@ -91,7 +91,7 @@ describe('Package', function () { } // function to invoke when Webpack compiler is done - var webpackCallback = function (error, stats) { + const webpackCallback = function (error, stats) { if (error) { done.fail(error) } @@ -107,8 +107,8 @@ describe('Package', function () { }) function sandboxPath () { - var parts = [__dirname, '..', '..', '..', 'build', 'sandbox'] - for (var i = 0; i < arguments.length; i++) { + const parts = [__dirname, '..', '..', '..', 'build', 'sandbox'] + for (let i = 0; i < arguments.length; i++) { parts.push(arguments[i]) } return path.join.apply(null, parts) diff --git a/packages/neo4j-driver/test/internal/node/routing.driver.boltkit.test.js b/packages/neo4j-driver/test/internal/node/routing.driver.boltkit.test.js index 348f65d60..6f13f4f44 100644 --- a/packages/neo4j-driver/test/internal/node/routing.driver.boltkit.test.js +++ b/packages/neo4j-driver/test/internal/node/routing.driver.boltkit.test.js @@ -20,15 +20,13 @@ import neo4j from '../../../src' import { READ, WRITE } from '../../../src/driver' import boltStub from '../bolt-stub' -import RoutingTable from '../../../../bolt-connection/lib/rediscovery/routing-table' import { error, internal } from 'neo4j-driver-core' -import lolex from 'lolex' const { serverAddress: { ServerAddress } } = internal -const { SERVICE_UNAVAILABLE, SESSION_EXPIRED } = error +const { SESSION_EXPIRED } = error describe('#stub-routing routing driver with stub server', () => { it('should discover IPv6 servers', async () => { diff --git a/packages/neo4j-driver/test/internal/temporal-util.test.js b/packages/neo4j-driver/test/internal/temporal-util.test.js index 22b1785bf..0d696c2f2 100644 --- a/packages/neo4j-driver/test/internal/temporal-util.test.js +++ b/packages/neo4j-driver/test/internal/temporal-util.test.js @@ -18,7 +18,6 @@ */ import { int, internal } from 'neo4j-driver-core' -import { types } from '../../src' import testUtils from './test-utils' const { temporalUtil: util } = internal @@ -407,28 +406,3 @@ describe('#unit temporal-util', () => { expect(() => util.assertValidNanosecond(int(1222222222))).toThrow() }) }) - -function date (year, month, day) { - return new types.Date(int(year), int(month), int(day)) -} - -function localTime (hour, minute, second, nanosecond) { - return new types.LocalTime( - int(hour), - int(minute), - int(second), - int(nanosecond) - ) -} - -function localDateTime (year, month, day, hour, minute, second, nanosecond) { - return new types.LocalDateTime( - int(year), - int(month), - int(day), - int(hour), - int(minute), - int(second), - int(nanosecond) - ) -} diff --git a/packages/neo4j-driver/test/nested-statements.test.js b/packages/neo4j-driver/test/nested-statements.test.js index c12e606ad..262ee4f9a 100644 --- a/packages/neo4j-driver/test/nested-statements.test.js +++ b/packages/neo4j-driver/test/nested-statements.test.js @@ -23,8 +23,6 @@ import sharedNeo4j from './internal/shared-neo4j' describe('#integration session', () => { let driver let session - // eslint-disable-next-line no-unused-vars - let protocolVersion beforeEach(async () => { driver = neo4j.driver( @@ -33,7 +31,7 @@ describe('#integration session', () => { ) session = driver.session({ fetchSize: 2 }) - protocolVersion = await sharedNeo4j.cleanupAndGetProtocolVersion(driver) + await sharedNeo4j.cleanupAndGetProtocolVersion(driver) }) afterEach(async () => { @@ -82,7 +80,6 @@ describe('#integration session', () => { it('should give proper error when nesting queries within one session', done => { const size = 20 - const count = 0 const result = session.run('UNWIND range(1, $size) AS x RETURN x', { size: size }) diff --git a/packages/neo4j-driver/test/rx/navigation.test.js b/packages/neo4j-driver/test/rx/navigation.test.js index 6c37cc7f7..d49a03b65 100644 --- a/packages/neo4j-driver/test/rx/navigation.test.js +++ b/packages/neo4j-driver/test/rx/navigation.test.js @@ -18,9 +18,12 @@ */ import neo4j from '../../src' import sharedNeo4j from '../internal/shared-neo4j' +// eslint-disable-next-line no-unused-vars import RxSession from '../../src/session-rx' +// eslint-disable-next-line no-unused-vars import { Notification, Observable } from 'rxjs' import { materialize, toArray, map } from 'rxjs/operators' +// eslint-disable-next-line no-unused-vars import RxTransaction from '../../src/transaction-rx' describe('#integration-rx navigation', () => { diff --git a/packages/neo4j-driver/test/rx/nested-statements.test.js b/packages/neo4j-driver/test/rx/nested-statements.test.js index 79d31a1bd..0da36bfdc 100644 --- a/packages/neo4j-driver/test/rx/nested-statements.test.js +++ b/packages/neo4j-driver/test/rx/nested-statements.test.js @@ -28,6 +28,7 @@ import { catchError } from 'rxjs/operators' import neo4j from '../../src' +// eslint-disable-next-line no-unused-vars import RxSession from '../../src/session-rx' import sharedNeo4j from '../internal/shared-neo4j' diff --git a/packages/neo4j-driver/test/rx/session.test.js b/packages/neo4j-driver/test/rx/session.test.js index ffed49b9f..88d8aef4b 100644 --- a/packages/neo4j-driver/test/rx/session.test.js +++ b/packages/neo4j-driver/test/rx/session.test.js @@ -244,11 +244,11 @@ describe('#integration rx-session', () => { if (protocolVersion < 4.0) { return } - + const txcWork = new ConfigurableTransactionWork({ query: 'CREATE (:WithoutRetry) RETURN 5' }) - + const result = await session .executeWrite(txc => txcWork.work(txc)) .pipe(materialize(), toArray()) @@ -257,12 +257,11 @@ describe('#integration rx-session', () => { Notification.createNext(5), Notification.createComplete() ]) - + expect(txcWork.invocations).toBe(1) expect(await countNodes('WithoutRetry')).toBe(1) }, 60000) - it('should run transaction with retries on reactive failures', async () => { if (protocolVersion < 4.0) { return diff --git a/packages/neo4j-driver/test/rx/summary.test.js b/packages/neo4j-driver/test/rx/summary.test.js index 2c8bbcb15..9569c01f9 100644 --- a/packages/neo4j-driver/test/rx/summary.test.js +++ b/packages/neo4j-driver/test/rx/summary.test.js @@ -17,7 +17,9 @@ * limitations under the License. */ import neo4j from '../../src' +// eslint-disable-next-line no-unused-vars import RxSession from '../../src/session-rx' +// eslint-disable-next-line no-unused-vars import RxTransaction from '../../src/transaction-rx' import sharedNeo4j from '../internal/shared-neo4j' diff --git a/packages/neo4j-driver/test/rx/transaction.test.js b/packages/neo4j-driver/test/rx/transaction.test.js index 855957935..bd87a1a56 100644 --- a/packages/neo4j-driver/test/rx/transaction.test.js +++ b/packages/neo4j-driver/test/rx/transaction.test.js @@ -17,17 +17,16 @@ * limitations under the License. */ -import { Notification, throwError } from 'rxjs' +import { Notification } from 'rxjs' import { flatMap, materialize, toArray, concat, - map, - bufferCount, - catchError + map } from 'rxjs/operators' import neo4j from '../../src' +// eslint-disable-next-line no-unused-vars import RxSession from '../../src/session-rx' import RxTransaction from '../../src/transaction-rx' import sharedNeo4j from '../internal/shared-neo4j' diff --git a/packages/neo4j-driver/test/session.test.js b/packages/neo4j-driver/test/session.test.js index 920c3ec32..f20a08952 100644 --- a/packages/neo4j-driver/test/session.test.js +++ b/packages/neo4j-driver/test/session.test.js @@ -19,7 +19,6 @@ import neo4j from '../src' import { READ } from '../src/driver' -import SingleConnectionProvider from '../../bolt-connection/lib/connection-provider/connection-provider-single' import sharedNeo4j from './internal/shared-neo4j' import _ from 'lodash' import testUtils from './internal/test-utils' @@ -27,7 +26,6 @@ import { newError, error, queryType, - Session, internal, json } from 'neo4j-driver-core' @@ -42,8 +40,6 @@ const { PROTOCOL_ERROR, SESSION_EXPIRED } = error describe('#integration session', () => { let driver let session - // eslint-disable-next-line no-unused-vars - let protocolVersion beforeEach(async () => { driver = neo4j.driver( @@ -52,7 +48,7 @@ describe('#integration session', () => { ) session = driver.session() - protocolVersion = await sharedNeo4j.cleanupAndGetProtocolVersion(driver) + await sharedNeo4j.cleanupAndGetProtocolVersion(driver) }) afterEach(async () => { @@ -1233,19 +1229,4 @@ describe('#integration session', () => { .then(() => localDriver.close()) .then(() => done()) } - - function testUnsupportedQueryParameter (value, done) { - session - .run('RETURN $value', { value: value }) - .then(() => { - done.fail( - `Should not be possible to send ${value.constructor.name} ${value} as a query parameter` - ) - }) - .catch(error => { - expect(error.name).toEqual('Neo4jError') - expect(error.code).toEqual(neo4j.error.PROTOCOL_ERROR) - done() - }) - } }) diff --git a/packages/neo4j-driver/test/transaction.test.js b/packages/neo4j-driver/test/transaction.test.js index 11bf8ca8b..548f793f3 100644 --- a/packages/neo4j-driver/test/transaction.test.js +++ b/packages/neo4j-driver/test/transaction.test.js @@ -18,14 +18,11 @@ */ import neo4j from '../src' import sharedNeo4j from './internal/shared-neo4j' -import { ServerVersion } from '../src/internal/server-version' import { READ } from '../src/driver' describe('#integration transaction', () => { let driver let session - // eslint-disable-next-line no-unused-vars - let serverVersion beforeEach(async () => { driver = neo4j.driver( @@ -34,8 +31,7 @@ describe('#integration transaction', () => { ) session = driver.session() - const result = await session.run('MATCH (n) DETACH DELETE n') - serverVersion = ServerVersion.fromString(result.summary.server.version) + await session.run('MATCH (n) DETACH DELETE n') }) afterEach(async () => { diff --git a/packages/neo4j-driver/test/types/driver.test.ts b/packages/neo4j-driver/test/types/driver.test.ts index 02b96ea6f..fc3f00fa6 100644 --- a/packages/neo4j-driver/test/types/driver.test.ts +++ b/packages/neo4j-driver/test/types/driver.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import Driver, { AuthToken, Config, @@ -38,13 +40,11 @@ const authToken: AuthToken = dummy const scheme: string = authToken.scheme const principal: string = authToken.principal const credentials: string = authToken.credentials -const realm1: undefined = authToken.realm -const realm2: string = authToken.realm -const parameters1: undefined = authToken.parameters -const parameters2: { [key: string]: any } = <{ [key: string]: any }>( - authToken.parameters -) -const parameters3: Parameters = authToken.parameters +const realm1: undefined = authToken.realm as undefined +const realm2: string = authToken.realm as string +const parameters1: undefined = authToken.parameters as undefined +const parameters2: { [key: string]: any } = authToken.parameters as { [key: string]: any } +const parameters3: Parameters = authToken.parameters as Parameters const encryptionLevel: EncryptionLevel = dummy const encryptionLevelStr: string = encryptionLevel @@ -96,21 +96,22 @@ session1 console.log(record) }) }) - .then(() => session1.close()) + .then(async () => await session1.close()) + .catch(error => console.error(error)) -const close: Promise = driver.close() +const close: Promise = driver.close().catch(error => console.error(error)) driver.verifyConnectivity().then((serverInfo: ServerInfo) => { console.log(serverInfo.address) -}) +}).catch(error => console.error(error)) driver.supportsMultiDb().then((supported: boolean) => { - console.log(`multi database is supported? => ${supported}`) -}) + console.log(`multi database is supported? => ${supported ? 'yes' : 'no'}`) +}).catch(error => console.error(error)) driver.supportsTransactionConfig().then((supported: boolean) => { - console.log(`transaction config is supported? => ${supported}`) -}) + console.log(`transaction config is supported? => ${supported ? 'yes' : 'no'}`) +}).catch(error => console.error(error)) const rxSession1: RxSession = driver.rxSession() const rxSession2: RxSession = driver.rxSession({ defaultAccessMode: READ }) diff --git a/packages/neo4j-driver/test/types/export.test.ts b/packages/neo4j-driver/test/types/export.test.ts index 8121604c5..d5d7c75ae 100644 --- a/packages/neo4j-driver/test/types/export.test.ts +++ b/packages/neo4j-driver/test/types/export.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import { Bookmarks } from 'neo4j-driver-core/types/internal/bookmarks' import driver, { DateTime, @@ -44,7 +46,7 @@ const driverConfiguration0 = driver.driver('driver', undefined, { logging: { level: 'info', logger: (level: 'info' | 'warn' | 'error' | 'debug', message?: string) => { - console.log(level + ' ' + message) + console.log(level + ' ' + (message ?? '')) } }, resolver: (address: string) => [address], diff --git a/packages/neo4j-driver/test/types/graph-types.test.ts b/packages/neo4j-driver/test/types/graph-types.test.ts index 0c8224736..2e16a62b5 100644 --- a/packages/neo4j-driver/test/types/graph-types.test.ts +++ b/packages/neo4j-driver/test/types/graph-types.test.ts @@ -16,6 +16,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable no-unused-vars */ import { @@ -50,7 +52,7 @@ const node2: Node = new Node(2, ['Person', 'Employee'], { }) const node2Id: number = node2.identity -type NodeProps = { name: string } +interface NodeProps { name: string } const node3: Node = new Node(2, ['Person', 'Employee'], { name: 'Alice' }) @@ -106,7 +108,7 @@ const rel6Start: number = rel6.start const rel6End: number = rel6.end const isRel6: boolean = rel6 instanceof UnboundRelationship -type RelationshipProps = { since: number } +interface RelationshipProps { since: number } const rel7: Relationship = new Relationship( 2, 3, @@ -120,8 +122,8 @@ const rel7Props: RelationshipProps = rel7.properties const rel7PropertySince: number = rel7.properties.since const rel8: UnboundRelationship< - number, - RelationshipProps +number, +RelationshipProps > = new UnboundRelationship(5, 'KNOWS', { since: 12345 }) @@ -159,5 +161,5 @@ if (isPath(pathAsObj)) { const path2: Path = new Path(node2, node2, [pathSegment2]) const path2Start: Node = path2.start const path2End: Node = path2.end -const path2Segments: PathSegment[] = path2.segments +const path2Segments: Array> = path2.segments const isPath2: boolean = path2 instanceof Path diff --git a/packages/neo4j-driver/test/types/index.test.ts b/packages/neo4j-driver/test/types/index.test.ts index d93a693b1..97dbbde01 100644 --- a/packages/neo4j-driver/test/types/index.test.ts +++ b/packages/neo4j-driver/test/types/index.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import { auth, AuthToken, @@ -65,7 +67,7 @@ const driver4: Driver = driver( 'bolt://localhost', auth.basic('neo4j', 'password'), { - resolver: address => Promise.resolve([address1, address2]) + resolver: async address => await Promise.resolve([address1, address2]) } ) diff --git a/packages/neo4j-driver/test/types/integer.test.ts b/packages/neo4j-driver/test/types/integer.test.ts index 542a8eced..82e99295b 100644 --- a/packages/neo4j-driver/test/types/integer.test.ts +++ b/packages/neo4j-driver/test/types/integer.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import { Integer, inSafeRange, diff --git a/packages/neo4j-driver/test/types/record.test.ts b/packages/neo4j-driver/test/types/record.test.ts index 6613e0353..0c8ff1b48 100644 --- a/packages/neo4j-driver/test/types/record.test.ts +++ b/packages/neo4j-driver/test/types/record.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import { Record } from 'neo4j-driver-core' interface Person { @@ -51,11 +53,11 @@ record3.forEach( (value: string | number, key: 'name' | 'age', record: Record) => {} ) -const record3Mapped: [ +const record3Mapped: Array<[ string | number, 'name' | 'age', Record -][] = record3.map((...args) => args) +]> = record3.map((...args) => args) const record1Entries: IterableIterator<[string, any]> = record1.entries() const record2Entries: IterableIterator<[string, any]> = record2.entries() diff --git a/packages/neo4j-driver/test/types/result-rx.test.ts b/packages/neo4j-driver/test/types/result-rx.test.ts index 701df4654..9e4ce006e 100644 --- a/packages/neo4j-driver/test/types/result-rx.test.ts +++ b/packages/neo4j-driver/test/types/result-rx.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import RxResult from '../../types/result-rx' const dummy: any = null @@ -24,23 +26,29 @@ const dummy: any = null const res: RxResult = dummy const pushed: Promise = res.push() +// eslint-disable-next-line @typescript-eslint/no-invalid-void-type const paused: void = res.pause() const resumed: Promise = res.resume() res.keys().subscribe({ - next: value => console.log(`keys: ${value}`), + next: value => console.log(`keys: ${value.reduce((acc, curr) => acc + ', ' + curr, '')}`), complete: () => console.log('keys complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`keys error: ${error}`) }) res.records().subscribe({ + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions,@typescript-eslint/no-base-to-string next: value => console.log(`record: ${value}`), complete: () => console.log('records complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`records error: ${error}`) }) res.consume().subscribe({ - next: value => console.log(`summary: ${value}`), + // eslint-disable-next-line @typescript-eslint/no-base-to-string + next: value => console.log(`summary: ${value.toString()}`), complete: () => console.log('summary complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`summary error: ${error}`) }) diff --git a/packages/neo4j-driver/test/types/result.test.ts b/packages/neo4j-driver/test/types/result.test.ts index e88d0d0b9..549bae81f 100644 --- a/packages/neo4j-driver/test/types/result.test.ts +++ b/packages/neo4j-driver/test/types/result.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import { Record, ResultSummary, Result } from 'neo4j-driver-core' const dummy: any = null diff --git a/packages/neo4j-driver/test/types/session-rx.test.ts b/packages/neo4j-driver/test/types/session-rx.test.ts index 9c3e1ceed..8a6096b5e 100644 --- a/packages/neo4j-driver/test/types/session-rx.test.ts +++ b/packages/neo4j-driver/test/types/session-rx.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import RxSession from '../../types/session-rx' import RxTransaction from '../../types/transaction-rx' import { RxManagedTransaction } from '../../types' @@ -34,20 +36,25 @@ const dummy: any = null const intValue: Integer = Integer.fromInt(42) const keysObserver: Observer = { - next: value => console.log(`keys: ${value}`), + next: value => console.log(`keys: ${value.reduce((acc, curr) => acc + ', ' + curr, '')}`), complete: () => console.log('keys complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`keys error: ${error}`) } const recordsObserver: Observer = { - next: value => console.log(`record: ${value}`), + // eslint-disable-next-line @typescript-eslint/no-base-to-string + next: value => console.log(`record: ${value.toString()}`), complete: () => console.log('records complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`records error: ${error}`) } const summaryObserver: Observer = { - next: value => console.log(`summary: ${value}`), + // eslint-disable-next-line @typescript-eslint/no-base-to-string + next: value => console.log(`summary: ${value.toString()}`), complete: () => console.log('summary complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`summary error: ${error}`) } diff --git a/packages/neo4j-driver/test/types/session.test.ts b/packages/neo4j-driver/test/types/session.test.ts index c427f23b3..df3534465 100644 --- a/packages/neo4j-driver/test/types/session.test.ts +++ b/packages/neo4j-driver/test/types/session.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import { Integer, Record, @@ -61,8 +63,8 @@ const promise1: Promise = session.readTransaction((tx: Transaction) => { return 10 }) -const promise2: Promise = session.readTransaction((tx: Transaction) => { - return Promise.resolve('42') +const promise2: Promise = session.readTransaction(async (tx: Transaction) => { + return await Promise.resolve('42') }) const promise3: Promise = session.writeTransaction( @@ -72,8 +74,8 @@ const promise3: Promise = session.writeTransaction( ) const promise4: Promise = session.writeTransaction( - (tx: Transaction) => { - return Promise.resolve('42') + async (tx: Transaction) => { + return await Promise.resolve('42') } ) diff --git a/packages/neo4j-driver/test/types/spatial-types.test.ts b/packages/neo4j-driver/test/types/spatial-types.test.ts index 939a2ced9..41440cf10 100644 --- a/packages/neo4j-driver/test/types/spatial-types.test.ts +++ b/packages/neo4j-driver/test/types/spatial-types.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import { int, Integer, isPoint, Point } from 'neo4j-driver-core' const point1: Point = new Point(int(1), 2, 3) diff --git a/packages/neo4j-driver/test/types/temporal-types.test.ts b/packages/neo4j-driver/test/types/temporal-types.test.ts index b2d25798c..9be6ffcd1 100644 --- a/packages/neo4j-driver/test/types/temporal-types.test.ts +++ b/packages/neo4j-driver/test/types/temporal-types.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import { int, Integer, diff --git a/packages/neo4j-driver/test/types/transaction-managed-rx.test.ts b/packages/neo4j-driver/test/types/transaction-managed-rx.test.ts index 0aecebea3..c99c763b3 100644 --- a/packages/neo4j-driver/test/types/transaction-managed-rx.test.ts +++ b/packages/neo4j-driver/test/types/transaction-managed-rx.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import RxManagedTransaction from '../../types/transaction-managed-rx' import { Record, ResultSummary } from 'neo4j-driver-core' import RxResult from '../../types/result-rx' @@ -27,24 +29,30 @@ const dummy: any = null const stringObserver: Observer = { next: value => console.log(value), complete: () => console.log('complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`error: ${error}`) } const keysObserver: Observer = { - next: value => console.log(`keys: ${value}`), + next: value => console.log(`keys: ${value.reduce((acc, curr) => acc + ', ' + curr, '')}`), complete: () => console.log('keys complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`keys error: ${error}`) } const recordsObserver: Observer = { - next: value => console.log(`record: ${value}`), + // eslint-disable-next-line @typescript-eslint/no-base-to-string + next: value => console.log(`record: ${value.toString()}`), complete: () => console.log('records complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`records error: ${error}`) } const summaryObserver: Observer = { - next: value => console.log(`summary: ${value}`), + // eslint-disable-next-line @typescript-eslint/no-base-to-string + next: value => console.log(`summary: ${value.toString()}`), complete: () => console.log('summary complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`summary error: ${error}`) } diff --git a/packages/neo4j-driver/test/types/transaction-rx.test.ts b/packages/neo4j-driver/test/types/transaction-rx.test.ts index dbd2a4a3b..f703729f4 100644 --- a/packages/neo4j-driver/test/types/transaction-rx.test.ts +++ b/packages/neo4j-driver/test/types/transaction-rx.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import RxTransaction from '../../types/transaction-rx' import { Record, ResultSummary } from 'neo4j-driver-core' import RxResult from '../../types/result-rx' @@ -28,24 +30,30 @@ const dummy: any = null const stringObserver: Observer = { next: value => console.log(value), complete: () => console.log('complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`error: ${error}`) } const keysObserver: Observer = { - next: value => console.log(`keys: ${value}`), + next: value => console.log(`keys: ${value.reduce((acc, curr) => acc + ', ' + curr, '')}`), complete: () => console.log('keys complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`keys error: ${error}`) } const recordsObserver: Observer = { - next: value => console.log(`record: ${value}`), + // eslint-disable-next-line @typescript-eslint/no-base-to-string + next: value => console.log(`record: ${value.toString()}`), complete: () => console.log('records complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`records error: ${error}`) } const summaryObserver: Observer = { - next: value => console.log(`summary: ${value}`), + // eslint-disable-next-line @typescript-eslint/no-base-to-string + next: value => console.log(`summary: ${value.toString()}`), complete: () => console.log('summary complete'), + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions error: error => console.log(`summary error: ${error}`) } diff --git a/packages/neo4j-driver/test/types/transaction.test.ts b/packages/neo4j-driver/test/types/transaction.test.ts index 58121b66e..2119199a2 100644 --- a/packages/neo4j-driver/test/types/transaction.test.ts +++ b/packages/neo4j-driver/test/types/transaction.test.ts @@ -17,6 +17,8 @@ * limitations under the License. */ +/* eslint-disable @typescript-eslint/no-unused-vars */ + import { Record, ResultSummary, @@ -88,8 +90,8 @@ result4.subscribe({ tx.commit().then(() => { console.log('transaction committed') -}) +}).catch(error => console.error(error)) tx.rollback().then(() => { console.log('transaction rolled back') -}) +}).catch(error => console.error(error)) From 3d615f4478d21a5723b9b3959177695dfde040e1 Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Wed, 20 Apr 2022 13:33:35 +0200 Subject: [PATCH 11/13] Fix url parser --- packages/core/src/internal/url-util.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/internal/url-util.ts b/packages/core/src/internal/url-util.ts index c2e292fae..a8b5b44a4 100644 --- a/packages/core/src/internal/url-util.ts +++ b/packages/core/src/internal/url-util.ts @@ -151,7 +151,7 @@ function extractPort ( ): number { const port = typeof portString === 'string' ? parseInt(portString, 10) : portString - return port != null ? port : defaultPortForScheme(scheme) + return port != null && !isNaN(port) ? port : defaultPortForScheme(scheme) } function extractQuery ( From 7ab894b71462122167c771d73927ed441e32f422 Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Wed, 20 Apr 2022 15:08:54 +0200 Subject: [PATCH 12/13] Add linter to npm script --- package.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/package.json b/package.json index 8660455fd..ea78487f9 100644 --- a/package.json +++ b/package.json @@ -49,6 +49,11 @@ "lerna": "lerna", "prepare": "husky install", "lint-staged": "lint-staged", + "lint": "npm run lint::core && npm run lint::bolt-connection && npm run lint::bolt-connection && npm run lint::neo4j-driver-lite && npm run lint::neo4j-driver", + "lint::core": "npm run ts-standard::core -- packages/core/src/ && npm run ts-standard::core -- packages/core/test/", + "lint::bolt-connection": "npm run ts-standard::bolt-connection -- packages/bolt-connection/types/ && npm run standard -- packages/bolt-connection/src/ && npm run standard -- packages/bolt-connection/test/", + "lint::neo4j-driver-lite": "npm run ts-standard::neo4j-driver-lite -- packages/neo4j-driver-lite/src/ && npm run ts-standard::neo4j-driver-lite -- packages/neo4j-driver-lite/test/", + "lint::neo4j-driver": "npm run ts-standard::neo4j-driver -- packages/neo4j-driver/types/ && npm run ts-standard::neo4j-driver -- packages/neo4j-driver/test/types/ && npm run standard -- packages/neo4j-driver/src/ && npm run standard -- packages/neo4j-driver/test/**/*.js", "ts-standard": "npm run ts-standard::core && npm run ts-standard::bolt-connection && npm run ts-standard::neo4j-driver-lite && npm run ts-standard::neo4j-driver", "ts-standard::core": "ts-standard --fix --project ./packages/core/tsconfig.json", "ts-standard::bolt-connection": "ts-standard --fix --project ./packages/bolt-connection/tsconfig.json", From 1db794afb48b9e7597355b911ee226d72fc28311 Mon Sep 17 00:00:00 2001 From: Antonio Barcelos Date: Wed, 20 Apr 2022 15:41:13 +0200 Subject: [PATCH 13/13] Add linter to the pipeline --- package.json | 3 ++- testkit/unittests.py | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index ea78487f9..5e1a6db33 100644 --- a/package.json +++ b/package.json @@ -49,11 +49,12 @@ "lerna": "lerna", "prepare": "husky install", "lint-staged": "lint-staged", - "lint": "npm run lint::core && npm run lint::bolt-connection && npm run lint::bolt-connection && npm run lint::neo4j-driver-lite && npm run lint::neo4j-driver", + "lint": "npm run lint::core && npm run lint::bolt-connection && npm run lint::bolt-connection && npm run lint::neo4j-driver-lite && npm run lint::neo4j-driver && npm run lint::testkit-backend", "lint::core": "npm run ts-standard::core -- packages/core/src/ && npm run ts-standard::core -- packages/core/test/", "lint::bolt-connection": "npm run ts-standard::bolt-connection -- packages/bolt-connection/types/ && npm run standard -- packages/bolt-connection/src/ && npm run standard -- packages/bolt-connection/test/", "lint::neo4j-driver-lite": "npm run ts-standard::neo4j-driver-lite -- packages/neo4j-driver-lite/src/ && npm run ts-standard::neo4j-driver-lite -- packages/neo4j-driver-lite/test/", "lint::neo4j-driver": "npm run ts-standard::neo4j-driver -- packages/neo4j-driver/types/ && npm run ts-standard::neo4j-driver -- packages/neo4j-driver/test/types/ && npm run standard -- packages/neo4j-driver/src/ && npm run standard -- packages/neo4j-driver/test/**/*.js", + "lint::testkit-backend": "npm run standard -- packages/testkit-backend/src/**/*.js", "ts-standard": "npm run ts-standard::core && npm run ts-standard::bolt-connection && npm run ts-standard::neo4j-driver-lite && npm run ts-standard::neo4j-driver", "ts-standard::core": "ts-standard --fix --project ./packages/core/tsconfig.json", "ts-standard::bolt-connection": "ts-standard --fix --project ./packages/bolt-connection/tsconfig.json", diff --git a/testkit/unittests.py b/testkit/unittests.py index 89489ce7e..24e5a9c99 100644 --- a/testkit/unittests.py +++ b/testkit/unittests.py @@ -13,4 +13,5 @@ else: ignore = "--ignore=neo4j-driver-lite" + run_in_driver_repo(["npm", "run", "lint"]) run_in_driver_repo(["npm", "run", "test::unit", "--", ignore])