From 40e61d2aff5cbbe88350669713ce55da8f376af8 Mon Sep 17 00:00:00 2001 From: Marcin Lewandowski Date: Sat, 6 Apr 2024 13:47:07 +0200 Subject: [PATCH] unicorn eslint --- .eslintrc.js | 28 ++++++- src/Auth/Certificate.ts | 10 ++- src/Documents/Attachments/index.ts | 1 + src/Documents/BulkInsertOperation.ts | 12 +-- src/Documents/Changes/ChangesObservable.ts | 18 +++-- src/Documents/Changes/DatabaseChanges.ts | 47 +++++++---- .../Batches/SingleNodeBatchCommand.ts | 1 + src/Documents/Commands/GetDocumentsCommand.ts | 4 +- .../Commands/MultiGet/GetResponse.ts | 6 +- src/Documents/Commands/QueryCommand.ts | 4 +- src/Documents/DocumentStore.ts | 8 +- src/Documents/DocumentStoreBase.ts | 6 +- .../Identity/GenerateEntityIdOnTheClient.ts | 2 +- src/Documents/Identity/HiloIdGenerator.ts | 4 +- .../Identity/MultiTypeHiLoIdGenerator.ts | 2 +- .../Indexes/AbstractIndexDefinitionBuilder.ts | 6 +- src/Documents/Indexes/AdditionalAssembly.ts | 2 +- .../AbstractCountersIndexCreationTask.ts | 2 +- src/Documents/Indexes/Spatial.ts | 12 +-- .../AbstractTimeSeriesIndexCreationTask.ts | 1 + .../Attachments/GetAttachmentOperation.ts | 2 +- .../CompareExchangeSessionValue.ts | 24 ++++-- .../Operations/GetOngoingTaskInfoOperation.ts | 27 ++++--- .../Indexes/SetIndexesLockOperation.ts | 2 +- .../Operations/OperationCompletionAwaiter.ts | 6 +- src/Documents/Operations/OperationExecutor.ts | 2 +- .../MoreLikeThisUsingAnyDocument.ts | 2 +- .../Queries/Spatial/SpatialCriteria.ts | 15 ++-- .../Queries/Spatial/SpatialCriteriaFactory.ts | 2 +- .../Session/AbstractDocumentQuery.ts | 19 +++-- src/Documents/Session/DocumentSession.ts | 18 +++-- src/Documents/Session/IDocumentSession.ts | 12 ++- .../InMemoryDocumentSessionOperations.ts | 15 ++-- .../Session/Loaders/IncludeBuilderBase.ts | 20 +++-- .../Session/Loaders/MultiLoaderWithInclude.ts | 2 +- .../Session/Operations/BatchOperation.ts | 57 ++++++++----- .../Lazy/LazyConditionalLoadOperation.ts | 6 +- .../Operations/Lazy/LazyRevisionOperation.ts | 15 ++-- .../Operations/Lazy/LazySessionOperations.ts | 1 + .../Session/Operations/MultiGetOperation.ts | 2 +- src/Documents/Session/SessionEvents.ts | 1 + .../Session/SessionTimeSeriesBase.ts | 10 +-- .../TimeSeries/TimeSeriesValuesHelper.ts | 2 +- .../TimeSeries/TypedTimeSeriesRollupEntry.ts | 2 +- src/Documents/Session/Tokens/FacetToken.ts | 30 ++++--- src/Documents/Session/Tokens/OrderByToken.ts | 9 ++- .../Session/Tokens/TimeSeriesIncludesToken.ts | 12 ++- src/Documents/Session/Tokens/WhereToken.ts | 81 ++++++++++++------- src/Documents/Smuggler/BackupUtils.ts | 1 + .../Subscriptions/DocumentSubscriptions.ts | 2 +- .../Subscriptions/SubscriptionWorker.ts | 63 ++++++++++----- src/Http/ClusterRequestExecutor.ts | 7 +- src/Http/HttpCache.ts | 2 +- src/Http/RavenCommand.ts | 4 +- src/Http/RavenCommandResponsePipeline.ts | 11 +-- src/Http/RequestExecutor.ts | 45 ++++++----- src/Http/ServerNode.ts | 12 +-- src/Mapping/Json/Conventions/index.ts | 6 +- src/Mapping/Json/Replacers.ts | 4 +- src/Mapping/JsonOperation.ts | 6 +- src/Mapping/ObjectMapper.ts | 9 ++- src/Primitives/CaseInsensitiveKeysMap.ts | 2 +- src/Primitives/CaseInsensitiveStringSet.ts | 2 +- src/Primitives/TimeValue.ts | 9 ++- .../Operations/GetDatabaseRecordOperation.ts | 4 +- .../Tcp/TcpConnectionHeaderMessage.ts | 12 ++- src/Types/readable-stream.ts | 2 + src/Utility/LogUtil.ts | 1 + src/Utility/Stopwatch.ts | 2 +- src/Utility/StreamUtil.ts | 2 +- src/Utility/StringUtil.ts | 6 +- src/Utility/TcpUtils.ts | 8 +- src/Utility/TimeUtil.ts | 14 ++-- src/index.ts | 9 +-- .../GetNextOperationIdCommandTests.ts | 2 +- .../Operations/IndexesOperationsTests.ts | 1 + .../IDocumentQueryCustomizationMethodsTest.ts | 4 +- test/Documents/ReadmeSamples.ts | 2 +- test/Executor/RequestExecutorTests.ts | 2 +- test/Issues/RDBC_501.ts | 2 +- test/Mapping/ObjectMapperTests.ts | 6 +- test/Mapping/StreamJsonTests.ts | 2 +- .../Attachments/AttachmentsSessionTest.ts | 2 +- test/Ported/BulkInsert/BulkInsertsTest.ts | 5 +- test/Ported/Cluster/ClusterOperationTest.ts | 10 ++- .../Core/Streaming/DocumentStreaming.ts | 4 +- test/Ported/Core/Streaming/QueryStreaming.ts | 12 +-- .../Ported/Counters/BulkInsertCountersTest.ts | 2 +- .../Ported/Counters/CountersSingleNodeTest.ts | 4 +- test/Ported/Counters/SessionCountersTest.ts | 6 +- test/Ported/CustomEntityName.ts | 2 +- test/Ported/DatabaseSettingsOperationTest.ts | 4 +- test/Ported/Faceted/AggregationTest.ts | 24 +++--- test/Ported/HiLoTest.ts | 14 ++-- test/Ported/HttpsTest.ts | 4 +- test/Ported/Indexing/JavaScriptIndexTest.ts | 5 +- test/Ported/Issues/RavenDB_15076.ts | 4 +- test/Utils/AsyncQueue.ts | 2 +- 98 files changed, 579 insertions(+), 363 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 00edc8626..3830c4dc3 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -23,8 +23,25 @@ module.exports = { "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-inferrable-types": "off", "@typescript-eslint/no-unused-vars": "off", - "unicorn/prefer-node-protocol": "error", + + "unicorn/no-unnecessary-polyfills": "off", + "unicorn/prefer-string-replace-all": "off", + "unicorn/import-style": "off", + "unicorn/prefer-module": "off", + "unicorn/prefer-type-error": "off", + "unicorn/prefer-event-target": "off", + "unicorn/no-array-callback-reference": "off", + "unicorn/no-this-assignment": "off", + "unicorn/prefer-object-from-entries": "off", + "unicorn/prefer-ternary": "off", + "unicorn/prefer-code-point": "off", + "unicorn/prefer-switch": "off", + "unicorn/no-typeof-undefined": "off", + "unicorn/no-new-array": "off", + "unicorn/prefer-string-slice": "off", "unicorn/prevent-abbreviations": "off", + "unicorn/no-negated-condition": "off", + "unicorn/no-for-loop": "off", "unicorn/filename-case": "off", "unicorn/no-null": "off", "unicorn/catch-error-name": "off", @@ -33,6 +50,13 @@ module.exports = { "unicorn/explicit-length-check": "off", "unicorn/numeric-separators-style": "off", "unicorn/no-await-expression-member": "off", - "unicorn/no-zero-fractions": "off" + "unicorn/no-zero-fractions": "off", + "unicorn/prefer-native-coercion-functions": "off", + "unicorn/no-array-method-this-argument": "off", + "unicorn/no-useless-undefined": "off", + "unicorn/no-array-reduce": "off", + "unicorn/better-regex": "off", + "unicorn/prefer-spread": "off", + "unicorn/consistent-function-scoping": "off", } } diff --git a/src/Auth/Certificate.ts b/src/Auth/Certificate.ts index 3a8dd2d96..0ad907c56 100644 --- a/src/Auth/Certificate.ts +++ b/src/Auth/Certificate.ts @@ -32,15 +32,17 @@ export abstract class Certificate implements ICertificate { } switch (options.type) { - case Certificate.PEM: + case Certificate.PEM: { certificate = this.createPem(options.certificate, options.password, options.ca); break; - case Certificate.PFX: - + } + case Certificate.PFX: { certificate = this.createPfx(options.certificate, options.password, options.ca); break; - default: + } + default: { throwError("InvalidArgumentException", "Unsupported authOptions type: " + options.type); + } } return certificate; diff --git a/src/Documents/Attachments/index.ts b/src/Documents/Attachments/index.ts index a6a0fef95..acad8cf54 100644 --- a/src/Documents/Attachments/index.ts +++ b/src/Documents/Attachments/index.ts @@ -29,6 +29,7 @@ export class AttachmentResult { public data: stream.Readable, public details: AttachmentDetails, private _response: HttpResponse) { + // empty } public dispose() { diff --git a/src/Documents/BulkInsertOperation.ts b/src/Documents/BulkInsertOperation.ts index 53fdf69a3..d2ad6fc8d 100644 --- a/src/Documents/BulkInsertOperation.ts +++ b/src/Documents/BulkInsertOperation.ts @@ -111,7 +111,7 @@ export class BulkInsertOperation { } private async sendHeartBeat(): Promise { - if (new Date().getTime() - this._lastWriteToStream.getTime() < this._heartbeatCheckInterval) { + if (Date.now() - this._lastWriteToStream.getTime() < this._heartbeatCheckInterval) { return; } @@ -133,10 +133,10 @@ export class BulkInsertOperation { private static _checkServerVersion(serverVersion: string): boolean { if (serverVersion) { const versionParsed = serverVersion.split("."); - const major = parseInt(versionParsed[0], 10); - const minor = versionParsed.length > 1 ? parseInt(versionParsed[1]) : 0; - const build = versionParsed.length> 2 ? parseInt(versionParsed[2]) : 0; - if (isNaN(major) || isNaN(minor)) { + const major = Number.parseInt(versionParsed[0], 10); + const minor = versionParsed.length > 1 ? Number.parseInt(versionParsed[1]) : 0; + const build = versionParsed.length> 2 ? Number.parseInt(versionParsed[2]) : 0; + if (Number.isNaN(major) || Number.isNaN(minor)) { return false; } @@ -169,7 +169,7 @@ export class BulkInsertOperation { let errorFromServer: Error; try { errorFromServer = await this._getExceptionFromOperation(); - } catch (ee) { + } catch { // server is probably down, will propagate the original exception } diff --git a/src/Documents/Changes/ChangesObservable.ts b/src/Documents/Changes/ChangesObservable.ts index 39b303475..c7a75e648 100644 --- a/src/Documents/Changes/ChangesObservable.ts +++ b/src/Documents/Changes/ChangesObservable.ts @@ -23,7 +23,7 @@ export class ChangesObservable void): this; public on(event: "data" | "error", handler: ((value: T) => void) | ((error: Error) => void)): this { switch (event) { - case "data": + case "data": { // since allow multiple subscriptions on single object we cant register it multiple times // to avoid duplicates in notification if (!this._sendHandler) { @@ -35,7 +35,8 @@ export class ChangesObservable void); this._connectionState.inc(); break; - case "error": + } + case "error": { if (!this._errorHandler) { // register shared error handler this._errorHandler = (ex: Error) => this.error(ex); @@ -44,6 +45,7 @@ export class ChangesObservable void); break; + } } return this; @@ -60,7 +62,7 @@ export class ChangesObservable void) | ((error: Error) => void)): this { switch (event) { - case "data": + case "data": { if (this._subscribers.delete(handler as (value: T) => void)) { this._connectionState.dec(); } @@ -72,13 +74,15 @@ export class ChangesObservable void); if (!this._errorSubscribers.size) { this._connectionState.removeOnError(this._errorHandler); this._errorHandler = undefined; } break; + } } return this; @@ -94,11 +98,13 @@ export class ChangesObservable x(msg)); + for (const x of this._subscribers) x(msg); } public error(e: Error): void { - this._errorSubscribers.forEach(x => x(e)); + for (const x of this._errorSubscribers) { + x(e); + } } public ensureSubscribedNow(): Promise { diff --git a/src/Documents/Changes/DatabaseChanges.ts b/src/Documents/Changes/DatabaseChanges.ts index c3df04073..b8599a7bd 100644 --- a/src/Documents/Changes/DatabaseChanges.ts +++ b/src/Documents/Changes/DatabaseChanges.ts @@ -252,7 +252,7 @@ export class DatabaseChanges implements IDatabaseChanges { if (this.connected) { await this._send(unwatchCommand, value, values); } - } catch (e) { + } catch { // if we are not connected then we unsubscribed already // because connections drops with all subscriptions } @@ -476,24 +476,42 @@ export class DatabaseChanges implements IDatabaseChanges { private _notifySubscribers(type: string, value: any): void { switch (type) { - case "AggressiveCacheChange": - this._counters.forEach(state => state.send("AggressiveCache", AggressiveCacheChange.INSTANCE)); + case "AggressiveCacheChange": { + for (const state of this._counters.values()) { + state.send("AggressiveCache", AggressiveCacheChange.INSTANCE); + } break; - case "DocumentChange": - this._counters.forEach(state => state.send("Document", value)); + } + case "DocumentChange": { + for (const state of this._counters.values()) { + state.send("Document", value); + } break; - case "CounterChange": - this._counters.forEach(state => state.send("Counter", value)); + } + case "CounterChange": { + for (const state of this._counters.values()) { + state.send("Counter", value); + } break; - case "TimeSeriesChange": - this._counters.forEach(state => state.send("TimeSeries", value)); + } + case "TimeSeriesChange": { + for (const state of this._counters.values()) { + state.send("TimeSeries", value); + } break; - case "IndexChange": - this._counters.forEach(state => state.send("Index", value)); + } + case "IndexChange": { + for (const state of this._counters.values()) { + state.send("Index", value); + } break; - case "OperationStatusChange": - this._counters.forEach(state => state.send("Operation", value)); + } + case "OperationStatusChange": { + for (const state of this._counters.values()) { + state.send("Operation", value); + } break; + } case "TopologyChange": { const topologyChange = value as TopologyChange; const requestExecutor = this._requestExecutor; @@ -513,8 +531,9 @@ export class DatabaseChanges implements IDatabaseChanges { } break; } - default: + default: { throwError("NotSupportedException"); + } } } diff --git a/src/Documents/Commands/Batches/SingleNodeBatchCommand.ts b/src/Documents/Commands/Batches/SingleNodeBatchCommand.ts index 8da196e33..7a2265742 100644 --- a/src/Documents/Commands/Batches/SingleNodeBatchCommand.ts +++ b/src/Documents/Commands/Batches/SingleNodeBatchCommand.ts @@ -194,5 +194,6 @@ export class SingleNodeBatchCommand extends RavenCommand imp // eslint-disable-next-line @typescript-eslint/no-empty-function public dispose(): void { + // empty } } diff --git a/src/Documents/Commands/GetDocumentsCommand.ts b/src/Documents/Commands/GetDocumentsCommand.ts index 13d9edf4e..6d64fb9e8 100644 --- a/src/Documents/Commands/GetDocumentsCommand.ts +++ b/src/Documents/Commands/GetDocumentsCommand.ts @@ -283,9 +283,9 @@ export class GetDocumentsCommand extends RavenCommand { let newUri = request.uri; if (isGet) { - uniqueIds.forEach(x => { + for (const x of uniqueIds) { newUri += `&id=${encodeURIComponent(x || "")}`; - }); + } return { method: "GET", uri: newUri }; } else { diff --git a/src/Documents/Commands/MultiGet/GetResponse.ts b/src/Documents/Commands/MultiGet/GetResponse.ts index 6a44ed926..cf87f8420 100644 --- a/src/Documents/Commands/MultiGet/GetResponse.ts +++ b/src/Documents/Commands/MultiGet/GetResponse.ts @@ -90,10 +90,12 @@ export class GetResponse { case StatusCodes.NonAuthoritativeInformation: case StatusCodes.NoContent: case StatusCodes.NotModified: - case StatusCodes.NotFound: + case StatusCodes.NotFound: { return false; - default: + } + default: { return true; + } } } } diff --git a/src/Documents/Commands/QueryCommand.ts b/src/Documents/Commands/QueryCommand.ts index f022ce418..a231f51d2 100644 --- a/src/Documents/Commands/QueryCommand.ts +++ b/src/Documents/Commands/QueryCommand.ts @@ -145,9 +145,9 @@ export class QueryCommand extends RavenCommand { mapped.durationInMs = timings.DurationInMs; mapped.timings = timings.Timings ? {} : undefined; if (timings.Timings) { - Object.keys(timings.Timings).forEach(time => { + for (const time of Object.keys(timings.Timings)) { mapped.timings[StringUtil.uncapitalize(time)] = QueryCommand._mapTimingsToLocalObject(timings.Timings[time]); - }); + } } return mapped; } diff --git a/src/Documents/DocumentStore.ts b/src/Documents/DocumentStore.ts index 211f51295..ae4a678d9 100644 --- a/src/Documents/DocumentStore.ts +++ b/src/Documents/DocumentStore.ts @@ -104,7 +104,9 @@ export class DocumentStore extends DocumentStoreBase { value.Value.Dispose(); }*/ - this._databaseChanges.forEach(change => change.dispose()); + for (const change of this._databaseChanges.values()) { + change.dispose(); + } /* TODO // try to wait until all the async disposables are completed @@ -151,13 +153,13 @@ export class DocumentStore extends DocumentStoreBase { }) .then(() => { this._log.info(`Disposing request executors ${this._requestExecutors.size}`); - this._requestExecutors.forEach((executor, db) => { + for (const [db, executor] of this._requestExecutors.entries()) { try { executor.dispose(); } catch (err) { this._log.warn(err, `Error disposing request executor.`); } - }); + } }) .finally(() => this.emit("executorsDisposed")); } diff --git a/src/Documents/DocumentStoreBase.ts b/src/Documents/DocumentStoreBase.ts index d7c532c02..a79d09d4d 100644 --- a/src/Documents/DocumentStoreBase.ts +++ b/src/Documents/DocumentStoreBase.ts @@ -320,7 +320,7 @@ export abstract class DocumentStoreBase ): void; public removeSessionListener(eventName: any, eventHandler: (eventArgs: any) => void): void { const toRemove = this._eventHandlers - .filter(x => x[0] === eventName && x[1] === eventHandler)[0]; + .find(x => x[0] === eventName && x[1] === eventHandler); if (toRemove) { this._eventHandlers.splice(this._eventHandlers.indexOf(toRemove), 1); } @@ -329,7 +329,7 @@ export abstract class DocumentStoreBase public registerEvents(requestExecutor: RequestExecutor): void; public registerEvents(session: DocumentSession): void; public registerEvents(requestExecutorOrSession: RequestExecutor | DocumentSession): void { - this._eventHandlers.forEach(([eventName, eventHandler]) => { + for (const [eventName, eventHandler] of this._eventHandlers) { if (eventName === "failedRequest" || eventName === "topologyUpdated" || eventName === "beforeRequest" @@ -338,7 +338,7 @@ export abstract class DocumentStoreBase } else { (requestExecutorOrSession as DocumentSession).on(eventName, eventHandler); } - }); + } } public abstract maintenance: MaintenanceOperationExecutor; diff --git a/src/Documents/Identity/GenerateEntityIdOnTheClient.ts b/src/Documents/Identity/GenerateEntityIdOnTheClient.ts index adf0b60fa..46d089932 100644 --- a/src/Documents/Identity/GenerateEntityIdOnTheClient.ts +++ b/src/Documents/Identity/GenerateEntityIdOnTheClient.ts @@ -43,7 +43,7 @@ export class GenerateEntityIdOnTheClient { } resultCallback(null); return false; - } catch (e) { + } catch { throwError("InvalidOperationException", "Error trying to get ID from instance."); } } diff --git a/src/Documents/Identity/HiloIdGenerator.ts b/src/Documents/Identity/HiloIdGenerator.ts index 919ee9736..118920afb 100644 --- a/src/Documents/Identity/HiloIdGenerator.ts +++ b/src/Documents/Identity/HiloIdGenerator.ts @@ -71,7 +71,7 @@ export class HiloIdGenerator { if (range !== this._range) { continue; } - } catch (e) { + } catch { // previous task was faulted, we will try to replace it } @@ -91,7 +91,7 @@ export class HiloIdGenerator { try { // failed to replace, let's wait on the previous task await this._nextRangeTask.getValue(); - } catch (e) { + } catch { // previous task was faulted, we will try again } } diff --git a/src/Documents/Identity/MultiTypeHiLoIdGenerator.ts b/src/Documents/Identity/MultiTypeHiLoIdGenerator.ts index e754c843d..1d550f6c5 100644 --- a/src/Documents/Identity/MultiTypeHiLoIdGenerator.ts +++ b/src/Documents/Identity/MultiTypeHiLoIdGenerator.ts @@ -33,7 +33,7 @@ export class MultiTypeHiLoIdGenerator { : this._conventions.getCollectionNameForEntity(entity); if (!typeTagName) { - return Promise.resolve(null); + return null; } const tag = await this._conventions.transformClassCollectionNameToDocumentIdPrefix(typeTagName); diff --git a/src/Documents/Indexes/AbstractIndexDefinitionBuilder.ts b/src/Documents/Indexes/AbstractIndexDefinitionBuilder.ts index 8b2dfcd0e..785ec399e 100644 --- a/src/Documents/Indexes/AbstractIndexDefinitionBuilder.ts +++ b/src/Documents/Indexes/AbstractIndexDefinitionBuilder.ts @@ -60,9 +60,9 @@ export abstract class AbstractIndexDefinitionBuilder - Object.assign(result, { [item]: true }), {}); + const suggestions: { [suggestionOption: string]: boolean } = Object.fromEntries(Array.from(this.suggestionsOptions) + .map(( item) => + [item, true])); this._applyValues(indexDefinition, this.indexesStrings, (options, value) => options.indexing = value); diff --git a/src/Documents/Indexes/AdditionalAssembly.ts b/src/Documents/Indexes/AdditionalAssembly.ts index 4bc3fcdec..73bb6b1e5 100644 --- a/src/Documents/Indexes/AdditionalAssembly.ts +++ b/src/Documents/Indexes/AdditionalAssembly.ts @@ -11,8 +11,8 @@ export class AdditionalAssembly { public packageSourceUrl: string; public usings: string[]; - // eslint-disable-next-line @typescript-eslint/no-empty-function private constructor() { + // empty } public static onlyUsings(usings: string[]) { diff --git a/src/Documents/Indexes/Counters/AbstractCountersIndexCreationTask.ts b/src/Documents/Indexes/Counters/AbstractCountersIndexCreationTask.ts index 7c3af3f8a..dc3721a3b 100644 --- a/src/Documents/Indexes/Counters/AbstractCountersIndexCreationTask.ts +++ b/src/Documents/Indexes/Counters/AbstractCountersIndexCreationTask.ts @@ -4,5 +4,5 @@ import { AbstractCsharpCountersIndexCreationTask } from "./AbstractCsharpCounter * @deprecated Use AbstractCsharpCountersIndexCreationTask */ export abstract class AbstractCountersIndexCreationTask extends AbstractCsharpCountersIndexCreationTask { - + // empty } diff --git a/src/Documents/Indexes/Spatial.ts b/src/Documents/Indexes/Spatial.ts index b1bb39086..7faedbb1d 100644 --- a/src/Documents/Indexes/Spatial.ts +++ b/src/Documents/Indexes/Spatial.ts @@ -98,13 +98,11 @@ export class GeographySpatialOptionsFactory { /** * Defines a Geohash Prefix Tree index using a default Max Tree Level {@link SpatialOptions} */ - public defaultOptions(circleRadiusUnits?: SpatialUnits): SpatialOptions { - circleRadiusUnits = circleRadiusUnits || "Kilometers"; + public defaultOptions(circleRadiusUnits: SpatialUnits = "Kilometers"): SpatialOptions { return this.geohashPrefixTreeIndex(0, circleRadiusUnits); } - public boundingBoxIndex(circleRadiusUnits?: SpatialUnits): SpatialOptions { - circleRadiusUnits = circleRadiusUnits || "Kilometers"; + public boundingBoxIndex(circleRadiusUnits: SpatialUnits = "Kilometers"): SpatialOptions { const ops = new SpatialOptions(); ops.type = "Geography"; ops.strategy = "BoundingBox"; @@ -112,8 +110,7 @@ export class GeographySpatialOptionsFactory { return ops; } - public geohashPrefixTreeIndex(maxTreeLevel: number, circleRadiusUnits?: SpatialUnits): SpatialOptions { - circleRadiusUnits = circleRadiusUnits || "Kilometers"; + public geohashPrefixTreeIndex(maxTreeLevel: number, circleRadiusUnits: SpatialUnits = "Kilometers"): SpatialOptions { if (maxTreeLevel === 0) { maxTreeLevel = DEFAULT_GEOHASH_LEVEL; } @@ -126,8 +123,7 @@ export class GeographySpatialOptionsFactory { return opts; } - public quadPrefixTreeIndex(maxTreeLevel: number, circleRadiusUnits: SpatialUnits): SpatialOptions { - circleRadiusUnits = circleRadiusUnits || "Kilometers"; + public quadPrefixTreeIndex(maxTreeLevel: number, circleRadiusUnits: SpatialUnits = "Kilometers"): SpatialOptions { if (maxTreeLevel === 0) { maxTreeLevel = DEFAULT_QUAD_TREE_LEVEL; } diff --git a/src/Documents/Indexes/TimeSeries/AbstractTimeSeriesIndexCreationTask.ts b/src/Documents/Indexes/TimeSeries/AbstractTimeSeriesIndexCreationTask.ts index 30b4ee475..106d76255 100644 --- a/src/Documents/Indexes/TimeSeries/AbstractTimeSeriesIndexCreationTask.ts +++ b/src/Documents/Indexes/TimeSeries/AbstractTimeSeriesIndexCreationTask.ts @@ -4,4 +4,5 @@ import { AbstractCsharpCountersIndexCreationTask } from "../Counters/AbstractCsh * @deprecated use AbstractCsharpCountersIndexCreationTask */ export abstract class AbstractTimeSeriesIndexCreationTask extends AbstractCsharpCountersIndexCreationTask { + // empty } diff --git a/src/Documents/Operations/Attachments/GetAttachmentOperation.ts b/src/Documents/Operations/Attachments/GetAttachmentOperation.ts index 56b0d03bd..03fc77407 100644 --- a/src/Documents/Operations/Attachments/GetAttachmentOperation.ts +++ b/src/Documents/Operations/Attachments/GetAttachmentOperation.ts @@ -92,7 +92,7 @@ export class GetAttachmentCommand extends RavenCommand { let size = 0; const sizeHeader = response.headers.get("attachment-size") as string; if (sizeHeader) { - size = parseInt(sizeHeader, 10); + size = Number.parseInt(sizeHeader, 10); } const details: AttachmentDetails = { diff --git a/src/Documents/Operations/CompareExchange/CompareExchangeSessionValue.ts b/src/Documents/Operations/CompareExchange/CompareExchangeSessionValue.ts index b6a86bf58..ffe2d69e2 100644 --- a/src/Documents/Operations/CompareExchange/CompareExchangeSessionValue.ts +++ b/src/Documents/Operations/CompareExchange/CompareExchangeSessionValue.ts @@ -73,10 +73,12 @@ export class CompareExchangeSessionValue { return value; } case "Missing": - case "Deleted": + case "Deleted": { return null; - default: + } + default: { throwError("NotSupportedException", "Not supported state: " + this._state); + } } } @@ -105,13 +107,16 @@ export class CompareExchangeSessionValue { private _assertState() { switch (this._state) { case "None": - case "Missing": + case "Missing": { return; - case "Created": + } + case "Created": { throwError("InvalidOperationException", "The compare exchange value with key '" + this._key + "' was already stored."); break; - case "Deleted": + } + case "Deleted": { throwError("InvalidOperationException", "The compare exchange value with key '" + this._key + "' was already deleted."); + } } } @@ -152,12 +157,15 @@ export class CompareExchangeSessionValue { return new PutCompareExchangeCommandData(newValue.key, entityToInsert, newValue.index); } - case "Deleted": + case "Deleted": { return new DeleteCompareExchangeCommandData(this._key, this._index); - case "Missing": + } + case "Missing": { return null; - default: + } + default: { throwError("InvalidOperationException", "Not supported state: " + this._state); + } } } diff --git a/src/Documents/Operations/GetOngoingTaskInfoOperation.ts b/src/Documents/Operations/GetOngoingTaskInfoOperation.ts index 38bd071b1..545d7efcd 100644 --- a/src/Documents/Operations/GetOngoingTaskInfoOperation.ts +++ b/src/Documents/Operations/GetOngoingTaskInfoOperation.ts @@ -84,48 +84,56 @@ class GetOngoingTaskInfoCommand extends RavenCommand { let nestedTypes: NestedTypes = {}; switch (this._type) { - case "Replication": + case "Replication": { // nothing to do break; - case "RavenEtl": + } + case "RavenEtl": { nestedTypes = { configuration: "RavenEtlConfiguration", "configuration.transforms": "Transformation" }; break; - case "SqlEtl": + } + case "SqlEtl": { nestedTypes = { configuration: "SqlEtlConfiguration", "configuration.transforms": "Transformation" }; break; - case "Subscription": + } + case "Subscription": { nestedTypes = { lastBatchAckTime: "date", lastClientConnectionTime: "date" } break; - case "OlapEtl": + } + case "OlapEtl": { nestedTypes = { configuration: "OlapEtlConfiguration", "configuration.transforms": "Transformation" } break; - case "ElasticSearchEtl": + } + case "ElasticSearchEtl": { nestedTypes = { configuration: "ElasticSearchEtlConfiguration", "configuration.transforms": "Transformation" } break; - case "QueueEtl": + } + case "QueueEtl": { nestedTypes = { configuration: "QueueEtlConfiguration", "configuration.transforms": "Transformation" } break; - case "PullReplicationAsSink": + } + case "PullReplicationAsSink": { break; - case "Backup": + } + case "Backup": { nestedTypes = { lastFullBackup: "date", delayUntil: "date", @@ -136,6 +144,7 @@ class GetOngoingTaskInfoCommand extends RavenCommand { "nextBackup.originalBackupTime": "date", } break; + } } this.result = this._reviveResultTypes( diff --git a/src/Documents/Operations/Indexes/SetIndexesLockOperation.ts b/src/Documents/Operations/Indexes/SetIndexesLockOperation.ts index 0db20b256..525e864fa 100644 --- a/src/Documents/Operations/Indexes/SetIndexesLockOperation.ts +++ b/src/Documents/Operations/Indexes/SetIndexesLockOperation.ts @@ -44,7 +44,7 @@ export class SetIndexesLockOperation implements IMaintenanceOperation { private _filterAutoIndexes() { // Check for auto-indexes - we do not set lock for auto-indexes - if (this._parameters.indexNames.find(x => x.toLocaleLowerCase().startsWith("auto/"))) { + if (this._parameters.indexNames.some(x => x.toLocaleLowerCase().startsWith("auto/"))) { throwError("InvalidArgumentException", "Indexes list contains Auto-Indexes. " + "Lock Mode is not set for Auto-Indexes."); } diff --git a/src/Documents/Operations/OperationCompletionAwaiter.ts b/src/Documents/Operations/OperationCompletionAwaiter.ts index ad7b03281..8b3c7ab80 100644 --- a/src/Documents/Operations/OperationCompletionAwaiter.ts +++ b/src/Documents/Operations/OperationCompletionAwaiter.ts @@ -53,12 +53,14 @@ export class OperationCompletionAwaiter { .then((operationStatusResult) => { const operationStatus = operationStatusResult.status as OperationStatus; switch (operationStatus) { - case "Completed": + case "Completed": { return; - case "Canceled": + } + case "Canceled": { throwError("OperationCanceledException", `Operation of ID ${this._id} has been canceled.`); break; + } case "Faulted": { const faultResult: OperationExceptionResult = operationStatusResult.result; const errorSchema = Object.assign({}, faultResult, {url: this._requestExecutor.getUrl()}); diff --git a/src/Documents/Operations/OperationExecutor.ts b/src/Documents/Operations/OperationExecutor.ts index b8b018073..aebfead4e 100644 --- a/src/Documents/Operations/OperationExecutor.ts +++ b/src/Documents/Operations/OperationExecutor.ts @@ -26,7 +26,7 @@ export class OperationExecutor { public constructor(store: IDocumentStore, databaseName?: string); public constructor(store: DocumentStoreBase, databaseName?: string) { this._store = store; - this._databaseName = databaseName ? databaseName : store.database; + this._databaseName = databaseName ?? store.database; if (!StringUtil.isNullOrWhitespace(this._databaseName)) { this._requestExecutor = store.getRequestExecutor(this._databaseName); } else { diff --git a/src/Documents/Queries/MoreLikeThis/MoreLikeThisUsingAnyDocument.ts b/src/Documents/Queries/MoreLikeThis/MoreLikeThisUsingAnyDocument.ts index 550740566..5fdb948b6 100644 --- a/src/Documents/Queries/MoreLikeThis/MoreLikeThisUsingAnyDocument.ts +++ b/src/Documents/Queries/MoreLikeThis/MoreLikeThisUsingAnyDocument.ts @@ -1,5 +1,5 @@ import { MoreLikeThisBase } from "./MoreLikeThisBase"; export class MoreLikeThisUsingAnyDocument extends MoreLikeThisBase { - + // empty } diff --git a/src/Documents/Queries/Spatial/SpatialCriteria.ts b/src/Documents/Queries/Spatial/SpatialCriteria.ts index 1cd98ea64..bef7b2816 100644 --- a/src/Documents/Queries/Spatial/SpatialCriteria.ts +++ b/src/Documents/Queries/Spatial/SpatialCriteria.ts @@ -23,20 +23,25 @@ export abstract class SpatialCriteria { let whereOperator: WhereOperator; switch (this._relation) { - case "Within": + case "Within": { whereOperator = "SpatialWithin"; break; - case "Contains": + } + case "Contains": { whereOperator = "SpatialContains"; break; - case "Disjoint": + } + case "Disjoint": { whereOperator = "SpatialDisjoint"; break; - case "Intersects": + } + case "Intersects": { whereOperator = "SpatialIntersects"; break; - default: + } + default: { throwError("InvalidArgumentException"); + } } return WhereToken.create(whereOperator, fieldName, null, new WhereOptions({ diff --git a/src/Documents/Queries/Spatial/SpatialCriteriaFactory.ts b/src/Documents/Queries/Spatial/SpatialCriteriaFactory.ts index 2b6750cf8..764347abf 100644 --- a/src/Documents/Queries/Spatial/SpatialCriteriaFactory.ts +++ b/src/Documents/Queries/Spatial/SpatialCriteriaFactory.ts @@ -9,8 +9,8 @@ export class SpatialCriteriaFactory { public static INSTANCE = new SpatialCriteriaFactory(); - // eslint-disable-next-line @typescript-eslint/no-empty-function private constructor() { + // empty } public relatesToShape(shapeWkt: string, relation: SpatialRelation): SpatialCriteria; diff --git a/src/Documents/Session/AbstractDocumentQuery.ts b/src/Documents/Session/AbstractDocumentQuery.ts index 1f35b62e8..aefebb61a 100644 --- a/src/Documents/Session/AbstractDocumentQuery.ts +++ b/src/Documents/Session/AbstractDocumentQuery.ts @@ -567,7 +567,7 @@ export abstract class AbstractDocumentQuery x.alias === possibleAlias)) { + if (!queryData.loadTokens.some(x => x.alias === possibleAlias)) { return; } @@ -608,7 +608,7 @@ export abstract class AbstractDocumentQuery x instanceof FieldsToFetchToken)[0]; + .find(x => x instanceof FieldsToFetchToken); if (fetchToken) { const idx = this._selectTokens.indexOf(fetchToken); @@ -1993,20 +1993,25 @@ export abstract class AbstractDocumentQuery { + for (const key of Object.keys(oldPatch.patch.values)) { newVals[key] = oldPatch.patch.values[key]; - }); + } - Object.keys(patchRequest.values).forEach(key => { + for (const key of Object.keys(patchRequest.values)) { newVals[key] = patchRequest.values[key]; - }); + } const newPatchRequest = new PatchRequest(); newPatchRequest.script = newScript; @@ -856,7 +856,7 @@ export class DocumentSession extends InMemoryDocumentSessionOperations const response = responses[i]; const tempReqTime = response.headers[HEADERS.REQUEST_TIME]; response.elapsed = sw.elapsed; - const totalTime = tempReqTime ? parseInt(tempReqTime, 10) : 0; + const totalTime = tempReqTime ? Number.parseInt(tempReqTime, 10) : 0; const timeItem = { url: requests[i].urlAndQuery, duration: totalTime @@ -1174,17 +1174,19 @@ export class DocumentSession extends InMemoryDocumentSessionOperations await this.advanced.requestExecutor.execute(cmd); switch (cmd.statusCode) { - case StatusCodes.NotModified: + case StatusCodes.NotModified: { return { entity: null, // value not changed changeVector } - case StatusCodes.NotFound: + } + case StatusCodes.NotFound: { this.registerMissing(id); return { entity: null, changeVector: null // value is missing } + } } const documentInfo = DocumentInfo.getNewDocumentInfo(cmd.result.results[0]); diff --git a/src/Documents/Session/IDocumentSession.ts b/src/Documents/Session/IDocumentSession.ts index e78acf051..8e3962c6f 100644 --- a/src/Documents/Session/IDocumentSession.ts +++ b/src/Documents/Session/IDocumentSession.ts @@ -100,17 +100,21 @@ export class SessionInfo { } switch (requestExecutor.conventions.readBalanceBehavior) { - case "None": + case "None": { result = await requestExecutor.getPreferredNode(); break; - case "RoundRobin": + } + case "RoundRobin": { result = await requestExecutor.getNodeBySessionId(this.getSessionId()); break; - case "FastestNode": + } + case "FastestNode": { result = await requestExecutor.getFastestNode(); break; - default: + } + default: { throwError("InvalidArgumentException", requestExecutor.conventions.readBalanceBehavior); + } } return result.currentNode; diff --git a/src/Documents/Session/InMemoryDocumentSessionOperations.ts b/src/Documents/Session/InMemoryDocumentSessionOperations.ts index e6c7c69e1..752059bdc 100644 --- a/src/Documents/Session/InMemoryDocumentSessionOperations.ts +++ b/src/Documents/Session/InMemoryDocumentSessionOperations.ts @@ -1240,13 +1240,13 @@ export abstract class InMemoryDocumentSessionOperations newValues.push(...newRange.entries); - localRange.entries.forEach(item => { + for (const item of localRange.entries) { if (item.timestamp.getTime() <= newRange.to.getTime()) { - return; + continue; } newValues.push(item); - }); + } localRange.entries = newValues; } @@ -1516,7 +1516,7 @@ export abstract class InMemoryDocumentSessionOperations for (const commandData of result.sessionCommands) { switch (commandData.type) { case "PUT": - case "DELETE": + case "DELETE": { if (commandData.changeVector) { throwError( "InvalidOperationException", @@ -1524,13 +1524,16 @@ export abstract class InMemoryDocumentSessionOperations + commandData.id + " is not supported when using a cluster transaction."); } break; + } case "CompareExchangeDELETE": - case "CompareExchangePUT": + case "CompareExchangePUT": { break; - default: + } + default: { throwError( "InvalidOperationException", "The command '" + commandData.type + "' is not supported in a cluster session."); + } } } } diff --git a/src/Documents/Session/Loaders/IncludeBuilderBase.ts b/src/Documents/Session/Loaders/IncludeBuilderBase.ts index 36732d509..a3ca478b2 100644 --- a/src/Documents/Session/Loaders/IncludeBuilderBase.ts +++ b/src/Documents/Session/Loaders/IncludeBuilderBase.ts @@ -225,10 +225,11 @@ export class IncludeBuilderBase { private static _assertValidType(type: TimeSeriesRangeType, time: TimeValue): void { switch (type) { - case "None": + case "None": { throwError("InvalidArgumentException", "Time range type cannot be set to 'None' when time is specified."); break; - case "Last": + } + case "Last": { if (time) { if (time.value <= 0) { throwError("InvalidArgumentException", "Time range type cannot be set to 'Last' when time is negative or zero."); @@ -238,8 +239,10 @@ export class IncludeBuilderBase { } throwError("InvalidArgumentException", "Time range type cannot be set to 'Last' when time is not specified."); break; - default: + } + default: { throwError("NotSupportedException", "Not supported time range type: " + type); + } } } @@ -268,16 +271,19 @@ export class IncludeBuilderBase { private static _assertValidTypeAndCount(type: TimeSeriesRangeType, count: number): void { switch (type) { - case "None": + case "None": { throwError("InvalidArgumentException", "Time range type cannot be set to 'None' when count is specified."); break; - case "Last": + } + case "Last": { if (count <= 0) { throwError("InvalidArgumentException", "Count have to be positive."); } break; - default: + } + default: { throwError("NotSupportedException", "Not supported time range type: " + type); + } } } @@ -313,7 +319,7 @@ export class IncludeBuilderBase { throwError("InvalidArgumentException", "IIncludeBuilder: Cannot use 'includeAllTimeSeries' after using 'includeTimeSeries' or 'includeAllTimeSeries'."); } - if (hashSet2.find(x => x.name === TIME_SERIES.ALL)) { + if (hashSet2.some(x => x.name === TIME_SERIES.ALL)) { throwError("InvalidArgumentException", "IIncludeBuilder: Cannot use 'includeTimeSeries' or 'includeAllTimeSeries' after using 'includeAllTimeSeries'."); } } diff --git a/src/Documents/Session/Loaders/MultiLoaderWithInclude.ts b/src/Documents/Session/Loaders/MultiLoaderWithInclude.ts index 105ad8eaf..6041b2e2d 100644 --- a/src/Documents/Session/Loaders/MultiLoaderWithInclude.ts +++ b/src/Documents/Session/Loaders/MultiLoaderWithInclude.ts @@ -60,7 +60,7 @@ export class MultiLoaderWithInclude implements ILoaderWithInclude { }); return singleResult ? - Object.keys(results).map(x => results[x]).filter(x => x)[0] as TResult : + Object.keys(results).map(x => results[x]).find(x => x) as TResult : results; } diff --git a/src/Documents/Session/Operations/BatchOperation.ts b/src/Documents/Session/Operations/BatchOperation.ts index d7f5c0c04..a7ea45c20 100644 --- a/src/Documents/Session/Operations/BatchOperation.ts +++ b/src/Documents/Session/Operations/BatchOperation.ts @@ -91,23 +91,29 @@ export class BatchOperation { const type = getCommandType(batchResult); switch (type) { - case "PUT": + case "PUT": { this._handlePut(i, batchResult, false); break; - case "ForceRevisionCreation": + } + case "ForceRevisionCreation": { this._handleForceRevisionCreation(batchResult); break; - case "DELETE": + } + case "DELETE": { this._handleDelete(batchResult); break; - case "CompareExchangePUT": + } + case "CompareExchangePUT": { this._handleCompareExchangePut(batchResult); break; - case "CompareExchangeDELETE": + } + case "CompareExchangeDELETE": { this._handleCompareExchangeDelete(batchResult); break; - default: + } + default: { throwError("InvalidOperationException", `Command '${type}' is not supported.`); + } } } @@ -119,44 +125,57 @@ export class BatchOperation { const type = getCommandType(batchResult); switch (type) { - case "PUT": + case "PUT": { this._handlePut(i, batchResult, true); break; - case "DELETE": + } + case "DELETE": { this._handleDelete(batchResult); break; - case "PATCH": + } + case "PATCH": { this._handlePatch(batchResult); break; - case "AttachmentPUT": + } + case "AttachmentPUT": { this._handleAttachmentPut(batchResult); break; - case "AttachmentDELETE": + } + case "AttachmentDELETE": { this._handleAttachmentDelete(batchResult); break; - case "AttachmentMOVE": + } + case "AttachmentMOVE": { this._handleAttachmentMove(batchResult); break; - case "AttachmentCOPY": + } + case "AttachmentCOPY": { this._handleAttachmentCopy(batchResult); break; + } case "CompareExchangePUT": case "CompareExchangeDELETE": - case "ForceRevisionCreation": + case "ForceRevisionCreation": { break; - case "Counters": + } + case "Counters": { this._handleCounters(batchResult); break; + } case "TimeSeries": - case "TimeSeriesWithIncrements": + case "TimeSeriesWithIncrements": { //TODO: RavenDB-13474 add to time series cache break; - case "TimeSeriesCopy": + } + case "TimeSeriesCopy": { break; - case "BatchPATCH": + } + case "BatchPATCH": { break; - default: + } + default: { throwError("InvalidOperationException", `Command '${type}' is not supported.`); + } } } diff --git a/src/Documents/Session/Operations/Lazy/LazyConditionalLoadOperation.ts b/src/Documents/Session/Operations/Lazy/LazyConditionalLoadOperation.ts index 464a0ec1d..95edcc4d4 100644 --- a/src/Documents/Session/Operations/Lazy/LazyConditionalLoadOperation.ts +++ b/src/Documents/Session/Operations/Lazy/LazyConditionalLoadOperation.ts @@ -59,19 +59,21 @@ export class LazyConditionalLoadOperation implements ILazyOper } switch (response.statusCode) { - case StatusCodes.NotModified: + case StatusCodes.NotModified: { this._result = { entity: null, changeVector: this._changeVector } as ConditionalLoadResult; return; - case StatusCodes.NotFound: + } + case StatusCodes.NotFound: { this._session.registerMissing(this._id); this._result = { entity: null, changeVector: null } as ConditionalLoadResult; return; + } } if (response.result) { diff --git a/src/Documents/Session/Operations/Lazy/LazyRevisionOperation.ts b/src/Documents/Session/Operations/Lazy/LazyRevisionOperation.ts index ef2086842..0bd6eec2c 100644 --- a/src/Documents/Session/Operations/Lazy/LazyRevisionOperation.ts +++ b/src/Documents/Session/Operations/Lazy/LazyRevisionOperation.ts @@ -74,20 +74,25 @@ export class LazyRevisionOperation implements ILazyOperation { this._getRevisionOperation.result = jsonArrayResult; switch (this._mode) { - case "Single": + case "Single": { this._result = this._getRevisionOperation.getRevision(this._clazz); break; - case "Multi": + } + case "Multi": { this._result = this._getRevisionOperation.getRevisionsFor(this._clazz); break; - case "Map": + } + case "Map": { this._result = this._getRevisionOperation.getRevisions(this._clazz); break; - case "ListOfMetadata": + } + case "ListOfMetadata": { this._result = this._getRevisionOperation.getRevisionsMetadataFor(); break; - default: + } + default: { throwError("InvalidArgumentException", "Invalid mode: " + this._mode); + } } } } diff --git a/src/Documents/Session/Operations/Lazy/LazySessionOperations.ts b/src/Documents/Session/Operations/Lazy/LazySessionOperations.ts index e13136bd9..145a0dc71 100644 --- a/src/Documents/Session/Operations/Lazy/LazySessionOperations.ts +++ b/src/Documents/Session/Operations/Lazy/LazySessionOperations.ts @@ -57,6 +57,7 @@ export class LazySessionOperations implements ILazySessionOperations { idPrefix: string, opts?: SessionLoadStartingWithOptions): Lazy> { + // eslint-disable-next-line unicorn/prefer-default-parameters opts = opts || null; opts = Object.assign({}, LoadStartingWithOperation.DEFAULT, opts); const operation = new LazyStartsWithOperation(idPrefix, opts, this._delegate); diff --git a/src/Documents/Session/Operations/MultiGetOperation.ts b/src/Documents/Session/Operations/MultiGetOperation.ts index a5184dd40..c534a62cb 100644 --- a/src/Documents/Session/Operations/MultiGetOperation.ts +++ b/src/Documents/Session/Operations/MultiGetOperation.ts @@ -14,7 +14,7 @@ export class MultiGetOperation { this._session.requestExecutor, this._session.conventions, requests, this._session.sessionInfo); } - // eslint-disable-next-line @typescript-eslint/no-empty-function public setResult(result: object): void { + // empty } } diff --git a/src/Documents/Session/SessionEvents.ts b/src/Documents/Session/SessionEvents.ts index 1053692ba..bfee26785 100644 --- a/src/Documents/Session/SessionEvents.ts +++ b/src/Documents/Session/SessionEvents.ts @@ -96,6 +96,7 @@ export class SessionBeforeQueryEventArgs { constructor( public session: InMemoryDocumentSessionOperations, public queryCustomization: IDocumentQueryCustomization) { + // empty } } diff --git a/src/Documents/Session/SessionTimeSeriesBase.ts b/src/Documents/Session/SessionTimeSeriesBase.ts index 14fbae2f0..495a22059 100644 --- a/src/Documents/Session/SessionTimeSeriesBase.ts +++ b/src/Documents/Session/SessionTimeSeriesBase.ts @@ -172,7 +172,7 @@ export class SessionTimeSeriesBase { const metadataTimeSeries = document.metadata[CONSTANTS.Documents.Metadata.TIME_SERIES] as string[]; if (metadataTimeSeries && TypeUtil.isArray(metadataTimeSeries)) { - if (!metadataTimeSeries.find(x => StringUtil.equalsIgnoreCase(x, this.name))) { + if (!metadataTimeSeries.some(x => StringUtil.equalsIgnoreCase(x, this.name))) { // the document is loaded in the session, but the metadata says that there is no such timeseries return []; } @@ -352,11 +352,11 @@ export class SessionTimeSeriesBase { if (fromDates.length) { from = fromDates[0].date; - fromDates.forEach(d => { + for (const d of fromDates) { if (DatesComparator.compare(d, leftDate(from)) < 0) { from = d.date; } - }); + } } else { from = null; } @@ -366,11 +366,11 @@ export class SessionTimeSeriesBase { if (toDates.length) { to = toDates[0].date; - toDates.forEach(d => { + for (const d of toDates) { if (DatesComparator.compare(d, rightDate(to)) > 0) { to = d.date; } - }) + } } else { to = null; } diff --git a/src/Documents/Session/TimeSeries/TimeSeriesValuesHelper.ts b/src/Documents/Session/TimeSeries/TimeSeriesValuesHelper.ts index 778ab5750..4cd3247f1 100644 --- a/src/Documents/Session/TimeSeries/TimeSeriesValuesHelper.ts +++ b/src/Documents/Session/TimeSeries/TimeSeriesValuesHelper.ts @@ -33,7 +33,7 @@ export class TimeSeriesValuesHelper { throwError("InvalidOperationException", "Invalid field mapping. Expected string or { field: string, name: string } object. Got: " + value); } - const nameAlreadyUsed = !!mapping.find(x => x.field === field || x.name === name); + const nameAlreadyUsed = mapping.some(x => x.field === field || x.name === name); if (nameAlreadyUsed) { throwError("InvalidOperationException", "All fields and names must be unique."); } diff --git a/src/Documents/Session/TimeSeries/TypedTimeSeriesRollupEntry.ts b/src/Documents/Session/TimeSeries/TypedTimeSeriesRollupEntry.ts index b8aebf4dd..4973e8bcd 100644 --- a/src/Documents/Session/TimeSeries/TypedTimeSeriesRollupEntry.ts +++ b/src/Documents/Session/TimeSeries/TypedTimeSeriesRollupEntry.ts @@ -90,7 +90,7 @@ export class TypedTimeSeriesRollupEntry { for (let i = 0; i < valuesCount; i++) { if (!counts[i]) { - averages[i] = NaN; + averages[i] = Number.NaN; } else { averages[i] = sums[i] / counts[i]; } diff --git a/src/Documents/Session/Tokens/FacetToken.ts b/src/Documents/Session/Tokens/FacetToken.ts index a66dc4daa..78b121969 100644 --- a/src/Documents/Session/Tokens/FacetToken.ts +++ b/src/Documents/Session/Tokens/FacetToken.ts @@ -173,20 +173,25 @@ export class FacetToken extends QueryToken { for (const value of aggregationValue) { let aggregationToken: FacetAggregationToken; switch (aggregationKey) { - case "Max": + case "Max": { aggregationToken = FacetAggregationToken.max(value.name, value.displayName); break; - case "Min": + } + case "Min": { aggregationToken = FacetAggregationToken.min(value.name, value.displayName); break; - case "Average": + } + case "Average": { aggregationToken = FacetAggregationToken.average(value.name, value.displayName); break; - case "Sum": + } + case "Sum": { aggregationToken = FacetAggregationToken.sum(value.name, value.displayName); break; - default : + } + default : { throwError("NotImplementedException", "Unsupported aggregation method: " + aggregationKey); + } } token._aggregations.push(aggregationToken); @@ -218,32 +223,37 @@ export class FacetAggregationToken extends QueryToken { public writeTo(writer: StringBuilder): void { switch (this._aggregation) { - case "Max": + case "Max": { writer .append("max(") .append(this._fieldName) .append(")"); break; - case "Min": + } + case "Min": { writer .append("min(") .append(this._fieldName) .append(")"); break; - case "Average": + } + case "Average": { writer .append("avg(") .append(this._fieldName) .append(")"); break; - case "Sum": + } + case "Sum": { writer .append("sum(") .append(this._fieldName) .append(")"); break; - default: + } + default: { throwError("InvalidArgumentException", "Invalid aggregation mode: " + this._aggregation); + } } if (StringUtil.isNullOrWhitespace(this._fieldDisplayName)) { diff --git a/src/Documents/Session/Tokens/OrderByToken.ts b/src/Documents/Session/Tokens/OrderByToken.ts index 8cc99b1f1..ddff99207 100644 --- a/src/Documents/Session/Tokens/OrderByToken.ts +++ b/src/Documents/Session/Tokens/OrderByToken.ts @@ -115,15 +115,18 @@ export class OrderByToken extends QueryToken { .append("')"); } else { switch (this._ordering) { - case "Long": + case "Long": { writer.append(" as long"); break; - case "Double": + } + case "Double": { writer.append(" as double"); break; - case "AlphaNumeric": + } + case "AlphaNumeric": { writer.append(" as alphaNumeric"); break; + } } } diff --git a/src/Documents/Session/Tokens/TimeSeriesIncludesToken.ts b/src/Documents/Session/Tokens/TimeSeriesIncludesToken.ts index 9e6382a76..4e48f0d73 100644 --- a/src/Documents/Session/Tokens/TimeSeriesIncludesToken.ts +++ b/src/Documents/Session/Tokens/TimeSeriesIncludesToken.ts @@ -63,12 +63,14 @@ export class TimeSeriesIncludesToken extends QueryToken { private static _writeTimeRangeTo(writer: StringBuilder, range: TimeSeriesTimeRange) { switch (range.type) { - case "Last": + case "Last": { writer .append("last("); break; - default: + } + default: { throwError("InvalidArgumentException", "Not supported time range type: " + range.type); + } } writer @@ -80,12 +82,14 @@ export class TimeSeriesIncludesToken extends QueryToken { private static _writeCountRangeTo(writer: StringBuilder, range: TimeSeriesCountRange) { switch (range.type) { - case "Last": + case "Last": { writer .append("last("); break; - default: + } + default: { throwError("InvalidArgumentException", "Not supported time range type: " + range.type); + } } writer diff --git a/src/Documents/Session/Tokens/WhereToken.ts b/src/Documents/Session/Tokens/WhereToken.ts index 0b65b37c2..026c80584 100644 --- a/src/Documents/Session/Tokens/WhereToken.ts +++ b/src/Documents/Session/Tokens/WhereToken.ts @@ -131,12 +131,14 @@ export class WhereToken extends QueryToken { private _writeMethod(writer): boolean { if (this.options.method) { switch (this.options.method.methodType) { - case "CmpXchg": + case "CmpXchg": { writer.append("cmpxchg("); break; - default: + } + default: { throwError("InvalidArgumentException", "Unsupported method: " + this.options.method.methodType); + } } let first: boolean = true; @@ -178,36 +180,46 @@ export class WhereToken extends QueryToken { } switch (this.whereOperator) { - case "Search": + case "Search": { writer.append("search("); break; - case "Lucene": + } + case "Lucene": { writer.append("lucene("); break; - case "StartsWith": + } + case "StartsWith": { writer.append("startsWith("); break; - case "EndsWith": + } + case "EndsWith": { writer.append("endsWith("); break; - case "Exists": + } + case "Exists": { writer.append("exists("); break; - case "SpatialWithin": + } + case "SpatialWithin": { writer.append("spatial.within("); break; - case "SpatialContains": + } + case "SpatialContains": { writer.append("spatial.contains("); break; - case "SpatialDisjoint": + } + case "SpatialDisjoint": { writer.append("spatial.disjoint("); break; - case "SpatialIntersects": + } + case "SpatialIntersects": { writer.append("spatial.intersects("); break; - case "Regex": + } + case "Regex": { writer.append("regex("); break; + } } this._writeInnerWhere(writer); @@ -242,32 +254,39 @@ export class WhereToken extends QueryToken { QueryToken.writeField(writer, this.fieldName); switch (this.whereOperator) { - case "Equals": + case "Equals": { writer.append(" = "); break; + } - case "NotEquals": + case "NotEquals": { writer.append(" != "); break; - case "GreaterThan": + } + case "GreaterThan": { writer .append(" > "); break; - case "GreaterThanOrEqual": + } + case "GreaterThanOrEqual": { writer .append(" >= "); break; - case "LessThan": + } + case "LessThan": { writer .append(" < "); break; - case "LessThanOrEqual": + } + case "LessThanOrEqual": { writer .append(" <= "); break; - default: + } + default: { this._specialOperator(writer); return; + } } if (!this._writeMethod(writer)) { @@ -277,27 +296,30 @@ export class WhereToken extends QueryToken { private _specialOperator(writer): void { switch (this.whereOperator) { - case "In": + case "In": { writer .append(" in ($") .append(this.parameterName) .append(")"); break; - case "AllIn": + } + case "AllIn": { writer .append(" all in ($") .append(this.parameterName) .append(")"); break; - case "Between": + } + case "Between": { writer .append(" between $") .append(this.options.fromParameterName) .append(" and $") .append(this.options.toParameterName); break; + } - case "Search": + case "Search": { writer .append(", $") .append(this.parameterName); @@ -306,23 +328,26 @@ export class WhereToken extends QueryToken { } writer.append(")"); break; + } case "Lucene": case "StartsWith": case "EndsWith": - case "Regex": + case "Regex": { writer .append(", $") .append(this.parameterName) .append(")"); break; - case "Exists": + } + case "Exists": { writer .append(")"); break; + } case "SpatialWithin": case "SpatialContains": case "SpatialDisjoint": - case "SpatialIntersects": + case "SpatialIntersects": { writer .append(", "); this.options.whereShape.writeTo(writer); @@ -334,8 +359,10 @@ export class WhereToken extends QueryToken { writer .append(")"); break; - default: + } + default: { throwError("InvalidArgumentException"); + } } } } diff --git a/src/Documents/Smuggler/BackupUtils.ts b/src/Documents/Smuggler/BackupUtils.ts index 199ea5f14..f23c3524d 100644 --- a/src/Documents/Smuggler/BackupUtils.ts +++ b/src/Documents/Smuggler/BackupUtils.ts @@ -6,6 +6,7 @@ import * as fs from "node:fs"; export class BackupUtils { // eslint-disable-next-line @typescript-eslint/no-empty-function private constructor() { + // empty } private static readonly LEGACY_INCREMENTAL_BACKUP_EXTENSION = ".ravendb-incremental-dump"; diff --git a/src/Documents/Subscriptions/DocumentSubscriptions.ts b/src/Documents/Subscriptions/DocumentSubscriptions.ts index d0ddcdcd6..136d9a743 100644 --- a/src/Documents/Subscriptions/DocumentSubscriptions.ts +++ b/src/Documents/Subscriptions/DocumentSubscriptions.ts @@ -412,7 +412,7 @@ export class DocumentSubscriptions implements IDisposable { return; } - this._subscriptions.forEach(((value, key) => key.dispose())); + for (const [key, value] of this._subscriptions.entries()) key.dispose(); } public async dropSubscriptionWorker(worker: SubscriptionWorker, database: string = null) { diff --git a/src/Documents/Subscriptions/SubscriptionWorker.ts b/src/Documents/Subscriptions/SubscriptionWorker.ts index c8f8d04c4..d4bec1e08 100644 --- a/src/Documents/Subscriptions/SubscriptionWorker.ts +++ b/src/Documents/Subscriptions/SubscriptionWorker.ts @@ -297,16 +297,18 @@ export class SubscriptionWorker implements IDisposable { this._ensureParser(socket); const x: any = await this._readNextObject(); switch (x.status) { - case "Ok": + case "Ok": { return { version: x.version, licensedFeatures: x.licensedFeatures } - case "AuthorizationFailed": + } + case "AuthorizationFailed": { throwError("AuthorizationException", "Cannot access database " + this._dbName + " because " + x.message); return; - case "TcpVersionMismatch": + } + case "TcpVersionMismatch": { if (x.version !== OUT_OF_RANGE_STATUS) { return { version: x.version, @@ -319,8 +321,10 @@ export class SubscriptionWorker implements IDisposable { throwError("InvalidOperationException", "Can't connect to database " + this._dbName + " because: " + x.message); break; - case "InvalidNetworkTopology": + } + case "InvalidNetworkTopology": { throwError("InvalidNetworkTopologyException", "Failed to connect to url " + url + " because " + x.message); + } } return { @@ -366,14 +370,16 @@ export class SubscriptionWorker implements IDisposable { // noinspection FallThroughInSwitchStatementJS switch (connectionStatus.status) { - case "Accepted": + case "Accepted": { break; - case "InUse": + } + case "InUse": { throwError("SubscriptionInUseException", "Subscription with id '" + this._options.subscriptionName + "' cannot be opened, because it's in use and the connection strategy is " + this._options.strategy); break; + } case "Closed": { const canReconnect = connectionStatus.data.CanReconnect || false; const subscriptionClosedError = getError("SubscriptionClosedException", @@ -382,16 +388,18 @@ export class SubscriptionWorker implements IDisposable { (subscriptionClosedError as any).canReconnect = canReconnect; throw subscriptionClosedError; } - case "Invalid": + case "Invalid": { throwError("SubscriptionInvalidStateException", "Subscription with id '" + this._options.subscriptionName + "' cannot be opened, because it is in invalid state. " + connectionStatus.exception); break; - case "NotFound": + } + case "NotFound": { throwError("SubscriptionDoesNotExistException", "Subscription with id '" + this._options.subscriptionName + "' cannot be opened, because it does not exist. " + connectionStatus.exception); break; + } case "Redirect": { if (this._options.strategy === "WaitForFree") { if (connectionStatus.data) { @@ -414,13 +422,15 @@ export class SubscriptionWorker implements IDisposable { (error as any).appropriateNode = appropriateNode; throw error; } - case "ConcurrencyReconnect": + case "ConcurrencyReconnect": { throwError("SubscriptionChangeVectorUpdateConcurrencyException", connectionStatus.message); break; - default: + } + default: { throwError("InvalidOperationException", "Subscription '" + this._options.subscriptionName + "' could not be opened, reason: " + connectionStatus.status); + } } } @@ -528,7 +538,7 @@ export class SubscriptionWorker implements IDisposable { } finally { try { await wrapWithTimeout(notifiedSubscriber, 15_000); - } catch (e) { + } catch { // ignore } } @@ -566,36 +576,45 @@ export class SubscriptionWorker implements IDisposable { } switch (receivedMessage.type) { - case "Data": + case "Data": { incomingBatch.push(receivedMessage); break; - case "Includes": + } + case "Includes": { includes.push(receivedMessage.includes); break; - case "CounterIncludes": + } + case "CounterIncludes": { counterIncludes.push({ counterIncludes: receivedMessage.includedCounterNames, includes: receivedMessage.counterIncludes }); break; - case "TimeSeriesIncludes": + } + case "TimeSeriesIncludes": { timeSeriesIncludes.push(receivedMessage.timeSeriesIncludes); break; - case "EndOfBatch": + } + case "EndOfBatch": { endOfBatch = true; break; - case "Confirm": + } + case "Confirm": { this._emitter.emit("afterAcknowledgment", batch); incomingBatch.length = 0; batch.items.length = 0; break; - case "ConnectionStatus": + } + case "ConnectionStatus": { this._assertConnectionState(receivedMessage); break; - case "Error": + } + case "Error": { this._throwSubscriptionError(receivedMessage); break; - default: + } + default: { this._throwInvalidServerResponse(receivedMessage); break; + } } } @@ -703,7 +722,7 @@ export class SubscriptionWorker implements IDisposable { this._redirectNode = indexAndNode.currentNode; this._logger.info("Subscription " + this._options.subscriptionName + ". Will modify redirect node from null to " + this._redirectNode.clusterTag); - } catch (e) { + } catch { // will let topology to decide this._logger.info("Subscription '" + this._options.subscriptionName + "'. Could not select the redirect node will keep it null."); } @@ -730,7 +749,7 @@ export class SubscriptionWorker implements IDisposable { } const maxErroneousPeriod = this._options.maxErroneousPeriod; - const erroneousPeriodDuration = new Date().getTime() - this._lastConnectionFailure.getTime(); + const erroneousPeriodDuration = Date.now() - this._lastConnectionFailure.getTime(); if (erroneousPeriodDuration > maxErroneousPeriod) { throwError("SubscriptionInvalidStateException", "Subscription connection was in invalid state for more than " diff --git a/src/Http/ClusterRequestExecutor.ts b/src/Http/ClusterRequestExecutor.ts index 6ea693c71..281f9eaff 100644 --- a/src/Http/ClusterRequestExecutor.ts +++ b/src/Http/ClusterRequestExecutor.ts @@ -86,7 +86,7 @@ export class ClusterRequestExecutor extends RequestExecutor { const executor = new ClusterRequestExecutor( authOptions, - documentConventions ? documentConventions : DocumentConventions.defaultConventions); + documentConventions ?? DocumentConventions.defaultConventions); executor._disableClientConfigurationUpdates = true; executor.firstTopologyUpdatePromise = executor._firstTopologyUpdate(initialUrls, null); @@ -104,11 +104,11 @@ export class ClusterRequestExecutor extends RequestExecutor { public async updateTopology(parameters: UpdateTopologyParameters): Promise { if (this._disposed) { - return Promise.resolve(false); + return false; } if (this._disableTopologyUpdates) { - return Promise.resolve(false); + return false; } const acquiredSemContext = acquireSemaphore(this._clusterTopologySemaphore, { timeout: parameters.timeoutInMs }); @@ -159,6 +159,7 @@ export class ClusterRequestExecutor extends RequestExecutor { public dispose(): void { // eslint-disable-next-line @typescript-eslint/no-empty-function this._clusterTopologySemaphore.take(() => { + // empty }); super.dispose(); } diff --git a/src/Http/HttpCache.ts b/src/Http/HttpCache.ts index 98eb74352..d0debadb9 100644 --- a/src/Http/HttpCache.ts +++ b/src/Http/HttpCache.ts @@ -100,7 +100,7 @@ export class ReleaseCacheItem { return Number.MAX_VALUE; } - return new Date().valueOf() - this.item.lastServerUpdate.valueOf(); + return Date.now() - this.item.lastServerUpdate.valueOf(); } public get mightHaveBeenModified() { diff --git a/src/Http/RavenCommand.ts b/src/Http/RavenCommand.ts index 9b3c76751..be0d7af5d 100644 --- a/src/Http/RavenCommand.ts +++ b/src/Http/RavenCommand.ts @@ -203,7 +203,7 @@ export abstract class RavenCommand { try { if (this._responseType === "Object") { - const contentLength: number = parseInt(response.headers.get("content-length"), 10); + const contentLength: number = Number.parseInt(response.headers.get("content-length"), 10); if (contentLength === 0) { closeHttpResponse(response); return "Automatic"; @@ -284,8 +284,8 @@ export abstract class RavenCommand { throwError("InvalidOperationException", "Response is invalid: " + cause.message, cause); } - // eslint-disable-next-line @typescript-eslint/no-empty-function public onResponseFailure(response: HttpResponse): void { + // empty } protected _pipeline() { diff --git a/src/Http/RavenCommandResponsePipeline.ts b/src/Http/RavenCommandResponsePipeline.ts index c5f5f7e64..0b45100d7 100644 --- a/src/Http/RavenCommandResponsePipeline.ts +++ b/src/Http/RavenCommandResponsePipeline.ts @@ -104,12 +104,9 @@ export class RavenCommandResponsePipeline extends EventEmitter { "Cannot use key case transform without doing parseJson() or parseJsonAsync() first."); } - if (!optsOrTransform || typeof optsOrTransform === "string") { - this._opts.streamKeyCaseTransform = - getObjectKeyCaseTransformProfile(optsOrTransform as CasingConvention, profile); - } else { - this._opts.streamKeyCaseTransform = optsOrTransform; - } + this._opts.streamKeyCaseTransform = !optsOrTransform || typeof optsOrTransform === "string" + ? getObjectKeyCaseTransformProfile(optsOrTransform as CasingConvention, profile) + : optsOrTransform; if (this._opts.jsonAsync) { this._opts.streamKeyCaseTransform.handleKeyValue = true; @@ -185,7 +182,7 @@ export class RavenCommandResponsePipeline extends EventEmitter { flush(callback) { let str = null; try { - str = Buffer.concat(bytesChunks).toString('utf-8'); + str = Buffer.concat(bytesChunks).toString("utf8"); } catch(err){ callback( getError("InvalidDataException", `Failed to concat / decode server response`, err)); diff --git a/src/Http/RequestExecutor.ts b/src/Http/RequestExecutor.ts index 130e83a74..af0cb5dc0 100644 --- a/src/Http/RequestExecutor.ts +++ b/src/Http/RequestExecutor.ts @@ -664,14 +664,18 @@ export class RequestExecutor implements IDisposable { } switch (this.conventions.readBalanceBehavior) { - case "None": + case "None": { return this._nodeSelector.getPreferredNode(); - case "RoundRobin": + } + case "RoundRobin": { return this._nodeSelector.getNodeBySessionId(sessionInfo ? sessionInfo.getSessionId() : 0); - case "FastestNode": + } + case "FastestNode": { return this._nodeSelector.getFastestNode(); - default: + } + default: { throwError("NotSupportedException", `Invalid read balance behavior: ${this.conventions.readBalanceBehavior}`); + } } } @@ -884,7 +888,7 @@ export class RequestExecutor implements IDisposable { } public static validateUrls(initialUrls: string[], authOptions: IAuthOptions) { - const cleanUrls = [...Array(initialUrls.length)]; + const cleanUrls = new Array(initialUrls.length); let requireHttps = !!authOptions?.certificate; for (let index = 0; index < initialUrls.length; index++) { const url = initialUrls[index]; @@ -923,12 +927,8 @@ export class RequestExecutor implements IDisposable { this._log.info("Initialize update topology timer."); const minInMs = 60 * 1000; - // eslint-disable-next-line @typescript-eslint/no-this-alias - const that = this; this._updateTopologyTimer = - new Timer(function timerActionUpdateTopology() { - return that._updateTopologyCallback(); - }, minInMs, minInMs); + new Timer(() => this._updateTopologyCallback(), minInMs, minInMs); } private async _executeOnSpecificNode( // this method is called `execute` in c# and java code @@ -1327,7 +1327,7 @@ export class RequestExecutor implements IDisposable { .then(commandResult => new IndexAndResponse(taskNumber, commandResult.response, commandResult.bodyStream)) .catch(err => { tasks[taskNumber] = null; - return Promise.reject(err); + throw err; }); if (nodes[i].clusterTag === chosenNode.clusterTag) { @@ -1437,19 +1437,23 @@ export class RequestExecutor implements IDisposable { responseBodyStream.resume(); const readBody = () => StreamUtil.readToEnd(responseBodyStream); switch (response.status) { - case StatusCodes.NotFound: + case StatusCodes.NotFound: { this._cache.setNotFound(url); switch (command.responseType) { - case "Empty": - return Promise.resolve(true); - case "Object": + case "Empty": { + return true; + } + case "Object": { return command.setResponseAsync(null, false) .then(() => true); - default: + } + default: { command.setResponseRaw(response, null); break; + } } return true; + } case StatusCodes.Forbidden: { const msg = await readBody(); @@ -1510,12 +1514,14 @@ export class RequestExecutor implements IDisposable { case StatusCodes.GatewayTimeout: case StatusCodes.RequestTimeout: case StatusCodes.BadGateway: - case StatusCodes.ServiceUnavailable: + case StatusCodes.ServiceUnavailable: { return this._handleServerDown( url, chosenNode, nodeIndex, command, req, response, await readBody(), null, sessionInfo, shouldRetry); - case StatusCodes.Conflict: + } + case StatusCodes.Conflict: { RequestExecutor._handleConflict(response, await readBody()); break; + } case StatusCodes.TooEarly: { if (!shouldRetry) { return false; @@ -1543,9 +1549,10 @@ export class RequestExecutor implements IDisposable { return true; } - default: + default: { command.onResponseFailure(response); ExceptionDispatcher.throwException(response, await readBody()); + } } } diff --git a/src/Http/ServerNode.ts b/src/Http/ServerNode.ts index 469d94a2c..46ef7850b 100644 --- a/src/Http/ServerNode.ts +++ b/src/Http/ServerNode.ts @@ -40,8 +40,8 @@ export class ServerNode { if (serverVersion) { const tokens = serverVersion.split("."); try { - const major = parseInt(tokens[0], 10); - const minor = parseInt(tokens[1], 10); + const major = Number.parseInt(tokens[0], 10); + const minor = Number.parseInt(tokens[1], 10); if (major > 5 || (major === 5 && minor >= 2)) { this.supportsAtomicClusterWrites = true; @@ -64,7 +64,7 @@ export class ServerNode { return nodes; } - Object.keys(topology.members).forEach(node => { + for (const node of Object.keys(topology.members)) { const member = topology.members[node]; nodes.push(new ServerNode({ @@ -72,9 +72,9 @@ export class ServerNode { clusterTag: node, serverRole: "Member" })); - }); + } - Object.keys(topology.watchers).forEach(node => { + for (const node of Object.keys(topology.watchers)) { const watcher = topology.watchers[node]; nodes.push(new ServerNode({ @@ -82,7 +82,7 @@ export class ServerNode { clusterTag: node, serverRole: "Member" })); - }); + } return nodes; } diff --git a/src/Mapping/Json/Conventions/index.ts b/src/Mapping/Json/Conventions/index.ts index 6beccad0e..ca24e31a5 100644 --- a/src/Mapping/Json/Conventions/index.ts +++ b/src/Mapping/Json/Conventions/index.ts @@ -28,9 +28,11 @@ export function getObjectKeyCaseTransformProfile( defaultTransform: CasingConvention, profile?: ObjectKeyCaseTransformProfile): ObjectKeyCaseTransformStreamOptions { switch (profile) { case "DOCUMENT_LOAD": - case "DOCUMENT_QUERY": + case "DOCUMENT_QUERY": { return Object.assign({ defaultTransform }, DOCUMENT_LOAD_KEY_CASE_TRANSFORM_PROFILE); - default: + } + default: { return { defaultTransform }; + } } } diff --git a/src/Mapping/Json/Replacers.ts b/src/Mapping/Json/Replacers.ts index 8136bfed6..f81ab94c7 100644 --- a/src/Mapping/Json/Replacers.ts +++ b/src/Mapping/Json/Replacers.ts @@ -3,7 +3,7 @@ export function pascalCaseReplacer(key, value) { const replacement = {}; for (const k in value) { if (Object.hasOwnProperty.call(value, k)) { - replacement[k && k.charAt(0).toUpperCase() + k.substring(1)] = value[k]; + replacement[k && k.charAt(0).toUpperCase() + k.slice(1)] = value[k]; } } return replacement; @@ -17,7 +17,7 @@ export function camelCaseReplacer(key, value) { const replacement = {}; for (const k in value) { if (Object.hasOwnProperty.call(value, k)) { - replacement[k && k.charAt(0).toLowerCase() + k.substring(1)] = value[k]; + replacement[k && k.charAt(0).toLowerCase() + k.slice(1)] = value[k]; } } diff --git a/src/Mapping/JsonOperation.ts b/src/Mapping/JsonOperation.ts index 1f4191d56..d80b2b095 100644 --- a/src/Mapping/JsonOperation.ts +++ b/src/Mapping/JsonOperation.ts @@ -40,8 +40,8 @@ export class JsonOperation { const newJsonProps: string[] = Object.keys(newJson); const oldJsonProps: string[] = Object.keys(originalJson); - const newFields = newJsonProps.filter(x => !oldJsonProps.find(y => y === x)); - const removedFields = oldJsonProps.filter(x => !newJsonProps.find(y => y === x)); + const newFields = new Set(newJsonProps.filter(x => !oldJsonProps.includes(x))); + const removedFields = oldJsonProps.filter(x => !newJsonProps.includes(x)); for (const field of removedFields) { if (!changes) { @@ -61,7 +61,7 @@ export class JsonOperation { continue; } - if (newFields.find(x => x === prop)) { + if (newFields.has(prop)) { if (!changes) { return true; } diff --git a/src/Mapping/ObjectMapper.ts b/src/Mapping/ObjectMapper.ts index 97234317f..d79afa5ef 100644 --- a/src/Mapping/ObjectMapper.ts +++ b/src/Mapping/ObjectMapper.ts @@ -85,8 +85,9 @@ export class TypesAwareObjectMapper implements ITypesAwareObjectMapper { .split(/[!.]/g); const fieldContext = this._getFieldContext(obj, objPathSegments); const fieldContexts = Array.isArray(fieldContext) ? fieldContext : [fieldContext]; - fieldContexts.forEach( - (c, i) => this._applyTypeToNestedProperty(typeName, c, knownTypes)); + for (const [i, c] of fieldContexts.entries()) { + this._applyTypeToNestedProperty(typeName, c, knownTypes); + } } return obj; @@ -315,14 +316,14 @@ export class TypesAwareObjectMapper implements ITypesAwareObjectMapper { } if (Array.isArray(fieldVal)) { - fieldVal.forEach((item, i) => { + for (const [i, item] of fieldVal.entries()) { this._applyTypeToNestedProperty(fieldTypeName, { field: i.toString(), parent: fieldVal, getValue: () => fieldVal[i], setValue: (val) => fieldVal[i] = val }, knownTypes); - }); + } return; } diff --git a/src/Primitives/CaseInsensitiveKeysMap.ts b/src/Primitives/CaseInsensitiveKeysMap.ts index bc5cdab97..7f1548975 100644 --- a/src/Primitives/CaseInsensitiveKeysMap.ts +++ b/src/Primitives/CaseInsensitiveKeysMap.ts @@ -7,7 +7,7 @@ function validateKey(key) { return; } - throw Error("Key must be a string."); + throw new Error("Key must be a string."); } export class CaseInsensitiveKeysMap { diff --git a/src/Primitives/CaseInsensitiveStringSet.ts b/src/Primitives/CaseInsensitiveStringSet.ts index e8a81fb76..683792c8b 100644 --- a/src/Primitives/CaseInsensitiveStringSet.ts +++ b/src/Primitives/CaseInsensitiveStringSet.ts @@ -2,7 +2,7 @@ import { CaseInsensitiveKeysStore } from "./CaseInsensitiveKeysStore"; function validateKey(key) { if (!(key && key.toLowerCase)) { - throw Error("Key must be a string."); + throw new Error("Key must be a string."); } } diff --git a/src/Primitives/TimeValue.ts b/src/Primitives/TimeValue.ts index 70ce19cda..f0fd3a659 100644 --- a/src/Primitives/TimeValue.ts +++ b/src/Primitives/TimeValue.ts @@ -131,8 +131,9 @@ export class TimeValue { } break; } - default: + default: { throwError("InvalidArgumentException", "Not supported unit: " + this._unit); + } } return str.toString().trim(); @@ -188,8 +189,9 @@ export class TimeValue { private static _getBoundsInSeconds(time: TimeValue): [number, number] { switch (time._unit) { - case "Second": + case "Second": { return [time._value, time._value]; + } case "Month": { const years = Math.floor(time._value / 12); let upperBound = years * TimeValue.SECONDS_IN_366_DAYS; @@ -202,8 +204,9 @@ export class TimeValue { return [lowerBound, upperBound]; } - default: + default: { throwError("InvalidArgumentException", "Not supported time value unit: " + time._unit); + } } } diff --git a/src/ServerWide/Operations/GetDatabaseRecordOperation.ts b/src/ServerWide/Operations/GetDatabaseRecordOperation.ts index 42d91a915..6a934f37c 100644 --- a/src/ServerWide/Operations/GetDatabaseRecordOperation.ts +++ b/src/ServerWide/Operations/GetDatabaseRecordOperation.ts @@ -71,11 +71,11 @@ export class GetDatabaseRecordCommand extends RavenCommand { + for (const index of Object.values(this.result.rollingIndexes)) { if (index.activeDeployments) { index.activeDeployments = GetDatabaseRecordCommand.mapRollingDeployment(dateUtil, index.activeDeployments as any); } - }); + } } const history = this.result.indexesHistory; diff --git a/src/ServerWide/Tcp/TcpConnectionHeaderMessage.ts b/src/ServerWide/Tcp/TcpConnectionHeaderMessage.ts index 7eed05641..2293d62d5 100644 --- a/src/ServerWide/Tcp/TcpConnectionHeaderMessage.ts +++ b/src/ServerWide/Tcp/TcpConnectionHeaderMessage.ts @@ -238,18 +238,22 @@ export function getOperationTcpVersion(operationType: OperationTypes, index: num // we don't check the if the index go out of range, since this is expected and means that we don't have switch (operationType) { case "Ping": - case "None": + case "None": { return -1; - case "Drop": + } + case "Drop": { return -2; + } case "Subscription": case "Replication": case "Cluster": case "Heartbeats": - case "TestConnection": + case "TestConnection": { return operationsToSupportedProtocolVersions.get(operationType)[index]; - default: + } + default: { throwError("InvalidArgumentException", "Invalid operation type: " + operationType); + } } } diff --git a/src/Types/readable-stream.ts b/src/Types/readable-stream.ts index 8c8f1c71d..545d283e0 100644 --- a/src/Types/readable-stream.ts +++ b/src/Types/readable-stream.ts @@ -11,6 +11,7 @@ declare module "readable-stream" { // eslint-disable-next-line @typescript-eslint/no-namespace namespace pipeable { export class Stream extends pipeable { + // empty } export interface ReadableOptions { @@ -272,6 +273,7 @@ declare module "readable-stream" { } export class PassThrough extends Transform { + // empty } export function pipeline(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException) => void): T; diff --git a/src/Utility/LogUtil.ts b/src/Utility/LogUtil.ts index 5e0ec026a..c737377e5 100644 --- a/src/Utility/LogUtil.ts +++ b/src/Utility/LogUtil.ts @@ -16,6 +16,7 @@ export function getLogger({ name = "ravendb", module = "" }): ILogger { if (!isDebug) { // eslint-disable-next-line @typescript-eslint/no-empty-function const noop = (msg: string) => { + // empty }; return { error: noop, diff --git a/src/Utility/Stopwatch.ts b/src/Utility/Stopwatch.ts index 66d022057..df3ab93eb 100644 --- a/src/Utility/Stopwatch.ts +++ b/src/Utility/Stopwatch.ts @@ -17,7 +17,7 @@ export class Stopwatch { } if (!this._endDate) { - return new Date().valueOf() - this._startDate.valueOf(); + return Date.now() - this._startDate.valueOf(); } return this._endDate.valueOf() - this._startDate.valueOf(); diff --git a/src/Utility/StreamUtil.ts b/src/Utility/StreamUtil.ts index fa0a3a5a7..2234f4ade 100644 --- a/src/Utility/StreamUtil.ts +++ b/src/Utility/StreamUtil.ts @@ -22,7 +22,7 @@ export async function readToEnd(readable: stream.Readable | stream.Stream): Prom readable.on("data", chunk => chunks.push(chunk)); await finishedAsync(readable); - return Buffer.concat(chunks).toString('utf-8'); + return Buffer.concat(chunks).toString("utf8"); } export function bufferToReadable(b: Buffer) { diff --git a/src/Utility/StringUtil.ts b/src/Utility/StringUtil.ts index 0ef0114e1..3bd37feed 100644 --- a/src/Utility/StringUtil.ts +++ b/src/Utility/StringUtil.ts @@ -42,7 +42,7 @@ export class StringUtil { return s.replace( /\{([\d]+)\}/g, (match: string, placeholder: string): string => { - const value: any = inputVars[parseInt(placeholder, 10)]; + const value: any = inputVars[Number.parseInt(placeholder, 10)]; return (TypeUtil.isNullOrUndefined(value) ? "" : value).toString(); }); @@ -91,11 +91,11 @@ export class StringUtil { } public static capitalize(s: string): string { - return s.charAt(0).toUpperCase() + s.substring(1); + return s.charAt(0).toUpperCase() + s.slice(1); } public static uncapitalize(s: string): string { - return s.charAt(0).toLowerCase() + s.substring(1); + return s.charAt(0).toLowerCase() + s.slice(1); } public static isCharacter(character: string): boolean { diff --git a/src/Utility/TcpUtils.ts b/src/Utility/TcpUtils.ts index 83c596803..85151a46b 100644 --- a/src/Utility/TcpUtils.ts +++ b/src/Utility/TcpUtils.ts @@ -16,7 +16,7 @@ export class TcpUtils { clientCertificate: IAuthOptions): Promise { const url = new URL(urlString); const host = url.hostname; - const port = parseInt(url.port, 10); + const port = Number.parseInt(url.port, 10); if (serverCertificate && clientCertificate) { return new Promise((resolve, reject) => { @@ -85,10 +85,12 @@ export class TcpUtils { private static _invokeNegotiation(info: TcpConnectionInfo, operationType: OperationTypes, negotiationCallback: NegotiationCallback, url: string, socket: Socket) { switch (operationType) { - case "Subscription": + case "Subscription": { return negotiationCallback(url, info, socket); - default: + } + default: { throwError("NotSupportedException", "Operation type '" + operationType + "' not supported"); + } } } } diff --git a/src/Utility/TimeUtil.ts b/src/Utility/TimeUtil.ts index c6caaa46f..3a18f0d13 100644 --- a/src/Utility/TimeUtil.ts +++ b/src/Utility/TimeUtil.ts @@ -6,9 +6,9 @@ export class TimeUtil { private static _parseMiddlePart(input: string) { const tokens = input.split(":"); - const hours = parseInt(tokens[0], 10); - const minutes = parseInt(tokens[1], 10); - const seconds = parseInt(tokens[2], 10); + const hours = Number.parseInt(tokens[0], 10); + const minutes = Number.parseInt(tokens[1], 10); + const seconds = Number.parseInt(tokens[2], 10); if (tokens.length !== 3) { throwError("InvalidArgumentException", "Unexpected duration format: " + input); @@ -60,18 +60,18 @@ export class TimeUtil { if (hasDays && hasMillis) { const tokens = text.split("."); - const days = parseInt(tokens[0], 10); - const millis = tokens[2] ? parseInt(tokens[2], 10) : 0; + const days = Number.parseInt(tokens[0], 10); + const millis = tokens[2] ? Number.parseInt(tokens[2], 10) : 0; return this._parseMiddlePart(tokens[1]) + millis + days * TimeUtil.MILLIS_IN_DAY; } else if (hasDays) { const tokens = text.split("."); - const days = parseInt(tokens[0], 10); + const days = Number.parseInt(tokens[0], 10); return this._parseMiddlePart(tokens[1]) + days * TimeUtil.MILLIS_IN_DAY; } else if (hasMillis) { const tokens = text.split("."); let fractionString = tokens[1]; fractionString = fractionString.padEnd(7, "0"); - const value = parseInt(fractionString, 10) / 10_000; + const value = Number.parseInt(fractionString, 10) / 10_000; return this._parseMiddlePart(tokens[0]) + value; } else { return this._parseMiddlePart(text); diff --git a/src/index.ts b/src/index.ts index 422f9cd1a..aa5b035ff 100644 --- a/src/index.ts +++ b/src/index.ts @@ -745,13 +745,10 @@ export * from "./ServerWide/Operations/ModifyDatabaseTopologyResult"; // MAPPING export { TypesAwareObjectMapper } from "./Mapping/ObjectMapper"; export { Mapping } from "./Mapping"; -import * as Json from "./Mapping/Json"; + // CONSTANTS export { CONSTANTS } from "./Constants"; -export { Json }; - -import { DocumentStore } from "./Documents/DocumentStore"; - -export default DocumentStore; +export * as Json from "./Mapping/Json"; +export { DocumentStore as default } from "./Documents/DocumentStore"; \ No newline at end of file diff --git a/test/Documents/Commands/GetNextOperationIdCommandTests.ts b/test/Documents/Commands/GetNextOperationIdCommandTests.ts index 5d98183f1..41e71ec2a 100644 --- a/test/Documents/Commands/GetNextOperationIdCommandTests.ts +++ b/test/Documents/Commands/GetNextOperationIdCommandTests.ts @@ -22,6 +22,6 @@ describe("GetNextOperationIdCommand", function () { await store.getRequestExecutor().execute(command); assert.ok(command.result); assert.ok(typeof command.result === "number"); - assert.ok(!isNaN(command.result)); + assert.ok(!Number.isNaN(command.result)); }); }); diff --git a/test/Documents/Operations/IndexesOperationsTests.ts b/test/Documents/Operations/IndexesOperationsTests.ts index 2c5181dd4..3b2ad3c9f 100644 --- a/test/Documents/Operations/IndexesOperationsTests.ts +++ b/test/Documents/Operations/IndexesOperationsTests.ts @@ -40,6 +40,7 @@ describe("Index operations", function () { class User { constructor(public name: string, public age?: number) { + // empty } } diff --git a/test/Documents/Queries/IDocumentQueryCustomizationMethodsTest.ts b/test/Documents/Queries/IDocumentQueryCustomizationMethodsTest.ts index b1c7d8848..c8d485438 100644 --- a/test/Documents/Queries/IDocumentQueryCustomizationMethodsTest.ts +++ b/test/Documents/Queries/IDocumentQueryCustomizationMethodsTest.ts @@ -22,11 +22,11 @@ describe("IDocumentQueryCustomizationMethodsTest", function () { this.map(BlogPost, b => { const result: TagResult[] = []; - b.tags.forEach(item => { + for (const item of b.tags) { result.push({ tag: item }); - }); + } return result; }) diff --git a/test/Documents/ReadmeSamples.ts b/test/Documents/ReadmeSamples.ts index dd0887a15..b65444ca9 100644 --- a/test/Documents/ReadmeSamples.ts +++ b/test/Documents/ReadmeSamples.ts @@ -333,7 +333,7 @@ describe("Readme samples", function () { print("// RQL"); print("// " + query.getIndexQuery().query); print("// ", query.getIndexQuery().queryParameters); - results.forEach(x => delete x["@metadata"]); + for (const x of results) delete x["@metadata"]; print("// " + util.inspect(results)); } }); diff --git a/test/Executor/RequestExecutorTests.ts b/test/Executor/RequestExecutorTests.ts index 8e4ca14c8..44406c198 100644 --- a/test/Executor/RequestExecutorTests.ts +++ b/test/Executor/RequestExecutorTests.ts @@ -41,7 +41,7 @@ describe("Request executor", function () { try { const cmd = new GetNextOperationIdCommand(); await executor.execute(cmd); - } catch (err) { + } catch { errorsCount++; } } diff --git a/test/Issues/RDBC_501.ts b/test/Issues/RDBC_501.ts index 32bee6fd2..94d55d6e3 100644 --- a/test/Issues/RDBC_501.ts +++ b/test/Issues/RDBC_501.ts @@ -19,7 +19,7 @@ class SymbolPrice { } class MarketSymbol { - + // empty } describe("RDBC-501", function () { diff --git a/test/Mapping/ObjectMapperTests.ts b/test/Mapping/ObjectMapperTests.ts index 66dca254c..1f6094602 100644 --- a/test/Mapping/ObjectMapperTests.ts +++ b/test/Mapping/ObjectMapperTests.ts @@ -26,6 +26,7 @@ describe("ObjectMapper", function () { class Person { constructor(public name: string) { + // empty } public sayHello() { @@ -38,16 +39,19 @@ describe("ObjectMapper", function () { public name: string, public releasedAt: Date ) { + // empty } } class Tree { constructor(public name: string) { + // empty } } class Order { constructor(public orderId: number, public isSent: false) { + // empty } } @@ -503,7 +507,7 @@ describe("ObjectMapper", function () { // eslint-disable-next-line @typescript-eslint/no-empty-function it.skip("can handle map having objects for keys", () => { - + // empty }); }); diff --git a/test/Mapping/StreamJsonTests.ts b/test/Mapping/StreamJsonTests.ts index 71d1910bf..e1ce13f7a 100644 --- a/test/Mapping/StreamJsonTests.ts +++ b/test/Mapping/StreamJsonTests.ts @@ -60,7 +60,7 @@ describe("stream-json parser and stringer", function () { }); it("stringer for query result response with negative result etag", (done) => { - const content = fs.readFileSync(path.join(__dirname, "../Assets/queryResult.json"), "utf-8"); + const content = fs.readFileSync(path.join(__dirname, "../Assets/queryResult.json"), "utf8"); const readable = new stream.Readable(); readable.push(content); readable.push(null); diff --git a/test/Ported/Attachments/AttachmentsSessionTest.ts b/test/Ported/Attachments/AttachmentsSessionTest.ts index aa0b636ad..c22cd2981 100644 --- a/test/Ported/Attachments/AttachmentsSessionTest.ts +++ b/test/Ported/Attachments/AttachmentsSessionTest.ts @@ -33,7 +33,7 @@ describe("Attachments Session", function () { const profileStream = Buffer.from([1, 2, 3]); const backgroundStream = Buffer.from([10, 20, 30, 40, 50]); const fileStream = new stream.Readable(); - [1, 2, 3, 4, 5].forEach(x => fileStream.push(Buffer.from(x.toString()))); + for (const x of [1, 2, 3, 4, 5]) fileStream.push(Buffer.from(x.toString())); fileStream.push(null); { diff --git a/test/Ported/BulkInsert/BulkInsertsTest.ts b/test/Ported/BulkInsert/BulkInsertsTest.ts index 778577d51..98b077dfe 100644 --- a/test/Ported/BulkInsert/BulkInsertsTest.ts +++ b/test/Ported/BulkInsert/BulkInsertsTest.ts @@ -92,7 +92,7 @@ describe("bulk insert", function () { } finally { try { await bulkInsert.finish(); - } catch (e) { + } catch { // ignore } } @@ -128,7 +128,7 @@ describe("bulk insert", function () { } finally { try { await bulkInsert.finish(); - } catch (e) { + } catch { //ignore } } @@ -287,6 +287,7 @@ describe("BulkInsertOperation._typeCheckStoreArgs() properly parses arguments", const typeCheckStoreArgs = BulkInsertOperation["_typeCheckStoreArgs"]; // eslint-disable-next-line @typescript-eslint/no-empty-function const expectedCallback = () => { + // empty }; const expectedId = "id"; const expectedMetadata = {} as IMetadataDictionary; diff --git a/test/Ported/Cluster/ClusterOperationTest.ts b/test/Ported/Cluster/ClusterOperationTest.ts index fce22c70d..c8ab96183 100644 --- a/test/Ported/Cluster/ClusterOperationTest.ts +++ b/test/Ported/Cluster/ClusterOperationTest.ts @@ -294,16 +294,18 @@ async function waitForTopologyStabilization(context: ClusterTestContext, s: stri let rehab = 0; let members = 0; - topo.nodes.forEach(n => { + for (const n of topo.nodes) { switch (n.serverRole) { - case "Rehab": + case "Rehab": { rehab++; break; - case "Member": + } + case "Member": { members++; break; + } } - }); + } return [rehab, members]; }, [rehabCount, memberCount], { diff --git a/test/Ported/Core/Streaming/DocumentStreaming.ts b/test/Ported/Core/Streaming/DocumentStreaming.ts index 5b3ca7188..b1bd5ec2a 100644 --- a/test/Ported/Core/Streaming/DocumentStreaming.ts +++ b/test/Ported/Core/Streaming/DocumentStreaming.ts @@ -67,13 +67,13 @@ describe("document streaming", function () { await StreamUtil.finishedAsync(queryStream); assert.strictEqual(items.length, 200); - items.forEach(item => { + for (const item of items) { assertStreamResultEntry(item, (doc: any) => { assert.ok(doc); assert.ok(doc.name); assert.ok(doc.lastName); }); - }); + } } } finally { newStore.dispose(); diff --git a/test/Ported/Core/Streaming/QueryStreaming.ts b/test/Ported/Core/Streaming/QueryStreaming.ts index 3122c75c4..f34c83bf1 100644 --- a/test/Ported/Core/Streaming/QueryStreaming.ts +++ b/test/Ported/Core/Streaming/QueryStreaming.ts @@ -142,7 +142,7 @@ describe("query streaming", function () { it("can stream query results with query statistics", async () => { await Promise.all([ prepareData(store, 100), - await usersByNameIndex.execute(store) + usersByNameIndex.execute(store) ]); await testContext.waitForIndexing(store); @@ -183,18 +183,18 @@ describe("query streaming", function () { assertStats(statsFromCallback); assert.equal(statsFromCallback, statsFromEvent); - items.forEach(x => assertStreamResultEntry(x, doc => { + for (const x of items) assertStreamResultEntry(x, doc => { assert.ok(doc instanceof User); assert.ok(doc.name); assert.ok(doc.lastName); - })); + }); } }); it("can stream raw query results", async () => { await Promise.all([ prepareData(store, 200), - await usersByNameIndex.execute(store) + usersByNameIndex.execute(store) ]); await testContext.waitForIndexing(store); @@ -240,7 +240,7 @@ describe("query streaming", function () { try { await Promise.all([ prepareData(newStore, 100), - await indexToUse.execute(store) + indexToUse.execute(store) ]); await testContext.waitForIndexing(store); @@ -295,7 +295,7 @@ describe("query streaming", function () { it("can stream raw query into stream", async () => { await Promise.all([ prepareData(store, 10), - await usersByNameIndex.execute(store) + usersByNameIndex.execute(store) ]); await testContext.waitForIndexing(store); diff --git a/test/Ported/Counters/BulkInsertCountersTest.ts b/test/Ported/Counters/BulkInsertCountersTest.ts index f277d8989..be307fd06 100644 --- a/test/Ported/Counters/BulkInsertCountersTest.ts +++ b/test/Ported/Counters/BulkInsertCountersTest.ts @@ -206,7 +206,7 @@ describe("BulkInsertCountersTest", function () { for (const counter of counters) { assertThat(counter.totalValue) - .isEqualTo(parseInt(counter.counterName, 10)); + .isEqualTo(Number.parseInt(counter.counterName, 10)); } }); }); diff --git a/test/Ported/Counters/CountersSingleNodeTest.ts b/test/Ported/Counters/CountersSingleNodeTest.ts index b1b550292..36db830a3 100644 --- a/test/Ported/Counters/CountersSingleNodeTest.ts +++ b/test/Ported/Counters/CountersSingleNodeTest.ts @@ -197,8 +197,8 @@ describe("CountersSingleNodeTest", function () { const { counters } = await store.operations.send(new GetCountersOperation("users/1-A", ["likes", "dislikes"])); assert.strictEqual(counters.length, 2); assert.strictEqual( - counters.filter(x => x.counterName === "likes")[0].totalValue, 5); - assert.strictEqual(counters.filter(x => x.counterName === "dislikes")[0].totalValue, 10); + counters.find(x => x.counterName === "likes").totalValue, 5); + assert.strictEqual(counters.find(x => x.counterName === "dislikes").totalValue, 10); }); it("multiSetAndGetViaBatch", async function() { diff --git a/test/Ported/Counters/SessionCountersTest.ts b/test/Ported/Counters/SessionCountersTest.ts index a582f4c7b..80bf51e8b 100644 --- a/test/Ported/Counters/SessionCountersTest.ts +++ b/test/Ported/Counters/SessionCountersTest.ts @@ -46,14 +46,14 @@ describe("SessionCountersTest", function () { new GetCountersOperation("users/1-A", ["likes", "downloads"]))).counters; assert.strictEqual(counters.length, 2); assert.strictEqual( - counters.filter(x => x.counterName === "likes")[0].totalValue, 100); + counters.find(x => x.counterName === "likes").totalValue, 100); assert.strictEqual( - counters.filter(x => x.counterName === "downloads")[0].totalValue, 500); + counters.find(x => x.counterName === "downloads").totalValue, 500); counters = (await store.operations.send(new GetCountersOperation("users/2-A", ["votes"]))).counters; assert.strictEqual(counters.length, 1); assert.strictEqual( - counters.filter(x => x.counterName === "votes")[0].totalValue, 1000); + counters.find(x => x.counterName === "votes").totalValue, 1000); } }); diff --git a/test/Ported/CustomEntityName.ts b/test/Ported/CustomEntityName.ts index fc4f8796d..a03fd3e4b 100644 --- a/test/Ported/CustomEntityName.ts +++ b/test/Ported/CustomEntityName.ts @@ -5,7 +5,7 @@ import { assertThat } from "../Utils/AssertExtensions"; describe("CustomEntityName", function () { const getChars = () => { - const basicChars = [...Array(31).keys()].map(x => { + const basicChars = [...new Array(31).keys()].map(x => { return String.fromCodePoint(x + 1); }); diff --git a/test/Ported/DatabaseSettingsOperationTest.ts b/test/Ported/DatabaseSettingsOperationTest.ts index 0b09711bf..c93cb9442 100644 --- a/test/Ported/DatabaseSettingsOperationTest.ts +++ b/test/Ported/DatabaseSettingsOperationTest.ts @@ -60,13 +60,13 @@ describe("DatabaseSettingsOperationTest", function () { async function checkIfOurValuesGotSaved(store: IDocumentStore, data: Record) { const settings = await getConfigurationSettings(store); - Object.keys(data).forEach(key => { + for (const key of Object.keys(data)) { const configurationValue = settings.settings[key]; assertThat(configurationValue) .isNotNull(); assertThat(configurationValue) .isEqualTo(data[key]); - }) + } } }); diff --git a/test/Ported/Faceted/AggregationTest.ts b/test/Ported/Faceted/AggregationTest.ts index 87b87be27..914cc3ceb 100644 --- a/test/Ported/Faceted/AggregationTest.ts +++ b/test/Ported/Faceted/AggregationTest.ts @@ -149,13 +149,13 @@ describe("AggregationTest", function () { let facetResult = r["product"]; assert.strictEqual(facetResult.values.length, 2); - assert.strictEqual(facetResult.values.filter(x => x.range === "milk")[0].sum, 12); - assert.strictEqual(facetResult.values.filter(x => x.range === "iphone")[0].sum, 3333); + assert.strictEqual(facetResult.values.find(x => x.range === "milk").sum, 12); + assert.strictEqual(facetResult.values.find(x => x.range === "iphone").sum, 3333); facetResult = r["currency"]; assert.strictEqual(facetResult.values.length, 2); - assert.strictEqual(facetResult.values.filter(x => x.range === "eur")[0].sum, 3336); - assert.strictEqual(facetResult.values.filter(x => x.range === "nis")[0].sum, 9); + assert.strictEqual(facetResult.values.find(x => x.range === "eur").sum, 3336); + assert.strictEqual(facetResult.values.find(x => x.range === "nis").sum, 9); } }); @@ -193,10 +193,10 @@ describe("AggregationTest", function () { const facetResult = r["product"]; assert.strictEqual(facetResult.values.length, 2); - assert.strictEqual(facetResult.values.filter(x => x.range === "milk")[0].max, 9); - assert.strictEqual(facetResult.values.filter(x => x.range === "milk")[0].min, 3); - assert.strictEqual(facetResult.values.filter(x => x.range === "iphone")[0].max, 3333); - assert.strictEqual(facetResult.values.filter(x => x.range === "iphone")[0].min, 3333); + assert.strictEqual(facetResult.values.find(x => x.range === "milk").max, 9); + assert.strictEqual(facetResult.values.find(x => x.range === "milk").min, 3); + assert.strictEqual(facetResult.values.find(x => x.range === "iphone").max, 3333); + assert.strictEqual(facetResult.values.find(x => x.range === "iphone").min, 3333); } }); @@ -286,16 +286,16 @@ describe("AggregationTest", function () { let facetResult = r["product"]; assert.strictEqual(Object.keys(r).length, 2); - assert.strictEqual(facetResult.values.filter(x => x.range === "milk")[0].sum, 12); - assert.strictEqual(facetResult.values.filter(x => x.range === "iphone")[0].sum, 3333); + assert.strictEqual(facetResult.values.find(x => x.range === "milk").sum, 12); + assert.strictEqual(facetResult.values.find(x => x.range === "iphone").sum, 3333); facetResult = r["total"]; assert.strictEqual(facetResult.values.length, 4); assert.strictEqual( - facetResult.values.filter(x => x.range === "total < 100")[0].sum, 12); + facetResult.values.find(x => x.range === "total < 100").sum, 12); assert.strictEqual( - facetResult.values.filter(x => x.range === "total >= 1500")[0].sum, 3333); + facetResult.values.find(x => x.range === "total >= 1500").sum, 3333); } }); diff --git a/test/Ported/HiLoTest.ts b/test/Ported/HiLoTest.ts index 38e378ade..bc2861629 100644 --- a/test/Ported/HiLoTest.ts +++ b/test/Ported/HiLoTest.ts @@ -42,7 +42,7 @@ describe("HiLo", function () { for (const numericPart of userIds .map(id => id.split("/")[1])) { - assert.ok(parseInt(numericPart, 10) < 33, + assert.ok(Number.parseInt(numericPart, 10) < 33, "Obtained ids should be less than 33, though they are:" + users.map(x => x.id).toString()); } @@ -196,9 +196,9 @@ describe("HiLo", function () { it("does not get another range when doing parallel requests", async () => { const parallelLevel = 32; - const users = Array.from(Array(parallelLevel).keys()).map(x => new User()); + const users = Array.from(new Array(parallelLevel).keys()).map(x => new User()); - const tasks = Array.from(Array(parallelLevel).keys()).map(async i => { + const tasks = Array.from(new Array(parallelLevel).keys()).map(async i => { const user = users[i]; const session = store.openSession(); await session.store(user); @@ -212,15 +212,15 @@ describe("HiLo", function () { .map(id => id.split("/")[1]) .map(x => x.split("-")[0])) { assert.ok(numericPart); - assert.ok(parseInt(numericPart, 10) < 33); + assert.ok(Number.parseInt(numericPart, 10) < 33); } }); it("does get another range when gets over max and leaves no gaps", async () => { const parallelLevel = 40; - const users = Array.from(Array(parallelLevel).keys()).map(x => new User()); + const users = Array.from(new Array(parallelLevel).keys()).map(x => new User()); - const tasks = Array.from(Array(parallelLevel).keys()).map(async i => { + const tasks = Array.from(new Array(parallelLevel).keys()).map(async i => { const user = users[i]; const session = store.openSession(); await session.store(user); @@ -232,7 +232,7 @@ describe("HiLo", function () { const idNumbers = users .map(x => x.id) .map(id => id.split("/")[1]) - .map(x => parseInt(x.split("-")[0], 10)); + .map(x => Number.parseInt(x.split("-")[0], 10)); assert.strictEqual(idNumbers.length, 40); diff --git a/test/Ported/HttpsTest.ts b/test/Ported/HttpsTest.ts index af8024c57..5dd7b8d84 100644 --- a/test/Ported/HttpsTest.ts +++ b/test/Ported/HttpsTest.ts @@ -224,7 +224,7 @@ describe("HttpsTest", function () { it("canUseServerGeneratedCertificate", async () => { const certificateRawData = await store.maintenance.server.send( - new CreateClientCertificateOperation("users-auth-test", { }, "Operator")); + new CreateClientCertificateOperation("users-auth-test", { /* empty */ }, "Operator")); const pfx = await extractPfx(certificateRawData); @@ -277,7 +277,7 @@ async function extractCertificate(certificateRawData: CertificateRawData) { if (entry.path.endsWith(".crt")) { const entryText = await readToEnd(entry); const lines = entryText.split(/\r?\n/); - cert = lines.slice(1, lines.length - 2).join("\r\n"); + cert = lines.slice(1, - 2).join("\r\n"); break; } else { entry.autodrain(); diff --git a/test/Ported/Indexing/JavaScriptIndexTest.ts b/test/Ported/Indexing/JavaScriptIndexTest.ts index 57bbf24fe..88a837523 100644 --- a/test/Ported/Indexing/JavaScriptIndexTest.ts +++ b/test/Ported/Indexing/JavaScriptIndexTest.ts @@ -591,7 +591,7 @@ class FanoutByPaymentsWithReduce extends AbstractJavaScriptIndexCreationTask { // keep reference to resolve function - if timeout finishes first, we don't want to wait for value! // eslint-disable-next-line @typescript-eslint/ban-types - let resolveToDelete: Function; + let resolveToDelete: valueResolver; let timeoutHandle: ReturnType; const timeoutErr = getError(