Skip to content

Commit db5ff57

Browse files
authored
Lots of linting (#50)
- Lots of linting - Fixed a couple methods' options not being optional
1 parent dd55ddc commit db5ff57

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+596
-772
lines changed

.eslintrc.cjs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
/* eslint-env node */
22
module.exports = {
3-
ignorePatterns: ['dist/*', 'scripts/*'],
43
extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
54
parser: '@typescript-eslint/parser',
65
plugins: ['@typescript-eslint'],
@@ -19,6 +18,13 @@ module.exports = {
1918
'caughtErrorsIgnorePattern': '^_',
2019
},
2120
],
21+
// Sometimes 'requires' is necessary
2222
'@typescript-eslint/no-var-requires': 'off',
2323
},
24+
parserOptions: {
25+
ecmaVersion: 'latest',
26+
sourceType: 'module',
27+
project: ['./tsconfig.json'],
28+
tsconfigRootDir: __dirname,
29+
},
2430
};

etc/astra-db-ts.api.md

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -194,13 +194,13 @@ export class Collection<Schema extends SomeDoc = SomeDoc> {
194194
findOneAndReplace(filter: Filter<Schema>, replacement: NoId<Schema>, options: FindOneAndReplaceOptions & {
195195
includeResultMetadata: true;
196196
}): Promise<ModifyResult<Schema>>;
197-
findOneAndReplace(filter: Filter<Schema>, replacement: NoId<Schema>, options: FindOneAndReplaceOptions & {
197+
findOneAndReplace(filter: Filter<Schema>, replacement: NoId<Schema>, options?: FindOneAndReplaceOptions & {
198198
includeResultMetadata?: false;
199199
}): Promise<WithId<Schema> | null>;
200200
findOneAndUpdate(filter: Filter<Schema>, update: UpdateFilter<Schema>, options: FindOneAndUpdateOptions & {
201201
includeResultMetadata: true;
202202
}): Promise<ModifyResult<Schema>>;
203-
findOneAndUpdate(filter: Filter<Schema>, update: UpdateFilter<Schema>, options: FindOneAndUpdateOptions & {
203+
findOneAndUpdate(filter: Filter<Schema>, update: UpdateFilter<Schema>, options?: FindOneAndUpdateOptions & {
204204
includeResultMetadata?: false;
205205
}): Promise<WithId<Schema> | null>;
206206
insertMany(documents: MaybeId<Schema>[], options?: InsertManyOptions): Promise<InsertManyResult<Schema>>;
@@ -528,7 +528,7 @@ export interface DbSpawnOptions {
528528
// @public
529529
export interface DefaultHttpClientOptions {
530530
client?: 'default';
531-
fetchH2?: any;
531+
fetchH2?: unknown;
532532
http1?: Http1Options;
533533
maxTimeMS?: number;
534534
preferHttp2?: boolean;
@@ -695,20 +695,20 @@ export class FindCursor<T, TRaw extends SomeDoc = SomeDoc> {
695695
clone(): FindCursor<TRaw, TRaw>;
696696
close(): void;
697697
get closed(): boolean;
698-
filter(filter: Filter<TRaw>): FindCursor<T, TRaw>;
698+
filter(filter: Filter<TRaw>): this;
699699
// @deprecated
700-
forEach(consumer: (doc: T) => boolean | void): Promise<void>;
700+
forEach(consumer: ((doc: T) => boolean) | ((doc: T) => void)): Promise<void>;
701701
hasNext(): Promise<boolean>;
702-
includeSimilarity(includeSimilarity?: boolean): FindCursor<T, TRaw>;
703-
limit(limit: number): FindCursor<T, TRaw>;
702+
includeSimilarity(includeSimilarity?: boolean): this;
703+
limit(limit: number): this;
704704
map<R>(mapping: (doc: T) => R): FindCursor<R, TRaw>;
705705
get namespace(): string;
706706
next(): Promise<T | null>;
707707
project<R = any, RRaw extends SomeDoc = SomeDoc>(projection: Projection): FindCursor<R, RRaw>;
708708
readBufferedDocuments(max?: number): TRaw[];
709709
rewind(): void;
710-
skip(skip: number): FindCursor<T, TRaw>;
711-
sort(sort: Sort): FindCursor<T, TRaw>;
710+
skip(skip: number): this;
711+
sort(sort: Sort): this;
712712
toArray(): Promise<T[]>;
713713
}
714714

@@ -944,7 +944,7 @@ export interface NumFilterOps {
944944

945945
// @public
946946
export class ObjectId {
947-
constructor(id?: string, validate?: boolean);
947+
constructor(id?: string | null, validate?: boolean);
948948
equals(other: unknown): boolean;
949949
getTimestamp(): Date;
950950
inspect(): string;
@@ -1138,7 +1138,7 @@ export class TooManyDocumentsToCountError extends DataAPIError {
11381138
}
11391139

11401140
// @public
1141-
export type TypeErr<S> = unknown & {
1141+
export type TypeErr<S> = {
11421142
[__error]: S;
11431143
};
11441144

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
"url": "git+https://github.com/datastax/astra-db-ts.git"
4949
},
5050
"scripts": {
51-
"lint": "eslint .",
51+
"lint": "eslint src/* tests/*",
5252
"test": "ts-mocha --paths -p tsconfig.json tests/unit/**/*.test.ts tests/integration/**/*.test.ts tests/integration/**/**/*.test.ts",
5353
"test:all": "env ASTRA_RUN_LONG_TESTS=1 ASTRA_RUN_ADMIN_TESTS=1 ts-mocha --paths -p tsconfig.json tests/unit/**/*.test.ts tests/integration/**/*.test.ts tests/integration/**/**/*.test.ts",
5454
"test:coverage": "nyc npm run test:all -- -b",

src/api/clients/data-api-http-client.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -120,26 +120,26 @@ export class DataAPIHttpClient extends HttpClient {
120120
throw new DataAPIHttpError(resp);
121121
}
122122

123-
const data: RawDataAPIResponse = JSON.parse(resp.body!, reviver);
123+
const data: RawDataAPIResponse = resp.body ? JSON.parse(resp.body, reviver) : {};
124124

125-
if (resp.status === 401 || (data.errors && data.errors?.length > 0 && data?.errors[0]?.message === 'UNAUTHENTICATED: Invalid token')) {
125+
if (resp.status === 401 || (data.errors && data.errors.length > 0 && data.errors[0]?.message === 'UNAUTHENTICATED: Invalid token')) {
126126
const fauxResponse = mkFauxErroredResponse('Authentication failed; is your token valid?');
127127
throw mkRespErrorFromResponse(DataAPIResponseError, info.command, fauxResponse);
128128
}
129129

130-
if (data.errors && data?.errors?.length > 0 && data?.errors[0]?.errorCode === 'COLLECTION_NOT_EXIST') {
131-
const name = data?.errors[0]?.message.split(': ')[1];
132-
throw new CollectionNotFoundError(info.namespace!, name);
130+
if (data.errors && data.errors.length > 0 && data.errors[0]?.errorCode === 'COLLECTION_NOT_EXIST') {
131+
const name = data.errors[0]?.message.split(': ')[1];
132+
throw new CollectionNotFoundError(info.namespace ?? '<unknown>', name);
133133
}
134134

135-
if (data?.errors && data?.errors.length > 0) {
135+
if (data.errors && data.errors.length > 0) {
136136
throw mkRespErrorFromResponse(DataAPIResponseError, info.command, data);
137137
}
138138

139139
const respData = {
140-
data: data?.data,
141-
status: data?.status,
142-
errors: data?.errors,
140+
data: data.data,
141+
status: data.status,
142+
errors: data.errors,
143143
}
144144

145145
if (this.monitorCommands) {

src/api/clients/devops-api-http-client.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export interface DevOpsAPIRequestInfo {
3333
path: string,
3434
method: HttpMethodStrings,
3535
data?: Record<string, any>,
36-
params?: Record<string, any>,
36+
params?: Record<string, string>,
3737
}
3838

3939
interface LongRunningRequestInfo {
@@ -80,7 +80,7 @@ export class DevOpsAPIHttpClient extends HttpClient {
8080
timeoutManager,
8181
});
8282

83-
const data = resp.body ? JSON.parse(resp.body) : undefined;
83+
const data = resp.body ? JSON.parse(resp.body) as Record<string, any> : undefined;
8484

8585
if (resp.status >= 400) {
8686
throw new DevOpsAPIResponseError(resp, data);
@@ -110,7 +110,7 @@ export class DevOpsAPIHttpClient extends HttpClient {
110110

111111
public async requestLongRunning(req: DevOpsAPIRequestInfo, info: LongRunningRequestInfo): Promise<DevopsAPIResponse> {
112112
const timeoutManager = this._mkTimeoutManager(info.options?.maxTimeMS);
113-
const isLongRunning = info?.options?.blocking !== false;
113+
const isLongRunning = info.options?.blocking !== false;
114114

115115
if (this.monitorCommands) {
116116
this.emitter.emit('adminCommandStarted', new AdminCommandStartedEvent(req, isLongRunning, timeoutManager.ms));
@@ -188,5 +188,7 @@ export class DevOpsAPIHttpClient extends HttpClient {
188188
}
189189

190190
function mkHeaders(token: string | undefined) {
191-
return { [DEFAULT_DEVOPS_API_AUTH_HEADER]: `Bearer ${token}` };
191+
return (token)
192+
? { [DEFAULT_DEVOPS_API_AUTH_HEADER]: `Bearer ${token}` }
193+
: {}
192194
}

src/api/clients/http-client.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ export abstract class HttpClient {
5858
}
5959

6060
const params = info.params ?? {};
61-
Object.keys(params).forEach(key => params[key] === undefined && delete params[key]);
6261

6362
const url = (Object.keys(params).length > 0)
6463
? `${info.url}?${new URLSearchParams(params).toString()}`

src/client/data-api-client.ts

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import {
1919
Caller,
2020
CustomHttpClientOptions,
2121
DataAPIClientOptions,
22-
DataAPIHttpOptions,
22+
DataAPIHttpOptions, DefaultHttpClientOptions,
2323
InternalRootClientOpts,
2424
} from '@/src/client/types';
2525
import TypedEmitter from 'typed-emitter';
@@ -61,7 +61,7 @@ export type DataAPIClientEvents =
6161
*/
6262
export const DataAPIClientEventEmitterBase = (() => {
6363
try {
64-
return require('events').EventEmitter as (new () => TypedEmitter<DataAPIClientEvents>);
64+
return (require('events') as { EventEmitter: (new () => TypedEmitter<DataAPIClientEvents>) }).EventEmitter;
6565
} catch (e) {
6666
throw new Error(`\`${LIB_NAME}\` requires the \`events\` module to be available for usage. Please provide a polyfill (e.g. the \`events\` package) or use a compatible environment.`);
6767
}
@@ -149,7 +149,7 @@ export class DataAPIClient extends DataAPIClientEventEmitterBase {
149149
};
150150

151151
if (Symbol.asyncDispose) {
152-
this[Symbol.asyncDispose] = this.close;
152+
this[Symbol.asyncDispose] = () => this.close();
153153
}
154154
}
155155

@@ -311,16 +311,12 @@ function buildFetchCtx(options: DataAPIClientOptions | undefined): FetchCtx {
311311
? options?.httpOptions?.client ?? 'default'
312312
: undefined;
313313

314-
const ctx = (() => {
315-
switch (clientType) {
316-
case 'fetch':
317-
return new FetchNative();
318-
case 'custom':
319-
return (options!.httpOptions as CustomHttpClientOptions).fetcher;
320-
default:
321-
return tryLoadFetchH2(clientType, options);
322-
}
323-
})();
314+
const ctx =
315+
(clientType === 'fetch')
316+
? new FetchNative() :
317+
(clientType === 'custom')
318+
? (options!.httpOptions as CustomHttpClientOptions).fetcher
319+
: tryLoadFetchH2(clientType, options)
324320

325321
return {
326322
ctx: ctx,
@@ -331,11 +327,13 @@ function buildFetchCtx(options: DataAPIClientOptions | undefined): FetchCtx {
331327

332328
function tryLoadFetchH2(clientType: string | undefined, options: DataAPIClientOptions | undefined): Fetcher {
333329
try {
334-
const preferHttp2 = (<any>options?.httpOptions)?.preferHttp2
330+
const httpOptions = options?.httpOptions as DefaultHttpClientOptions | undefined;
331+
332+
const preferHttp2 = httpOptions?.preferHttp2
335333
?? getDeprecatedPrefersHttp2(options)
336334
?? true
337335

338-
return new FetchH2(options?.httpOptions as any, preferHttp2);
336+
return new FetchH2(httpOptions, preferHttp2);
339337
} catch (e) {
340338
if (clientType === undefined) {
341339
return new FetchNative();
@@ -346,7 +344,7 @@ function tryLoadFetchH2(clientType: string | undefined, options: DataAPIClientOp
346344
}
347345

348346
// Shuts the linter up about 'preferHttp2' being deprecated
349-
function getDeprecatedPrefersHttp2(opts: DataAPIClientOptions | undefined | null) {
347+
function getDeprecatedPrefersHttp2(opts: DataAPIClientOptions | undefined | null): boolean | undefined {
350348
return opts?.[('preferHttp2' as any as null)!];
351349
}
352350

@@ -373,7 +371,7 @@ function validateHttpOpts(opts: DataAPIHttpOptions | undefined | null) {
373371
}
374372

375373
validateOption('httpOptions.client', opts.client, 'string', false, (client) => {
376-
if (client !== 'fetch' && client !== 'default' && client !== 'custom') {
374+
if (!['fetch', 'default', 'custom'].includes(client)) {
377375
throw new Error('Invalid httpOptions.client; expected \'fetch\', \'default\', \'custom\', or undefined');
378376
}
379377
});

src/common/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,5 @@
1313
// limitations under the License.
1414

1515
export * from './types';
16+
export * from './utils';
1617
export * from './token-providers';

src/common/utils.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright DataStax, Inc.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
import { nullish } from '@/src/common/types';
16+
17+
export function isNullish(t: unknown): t is nullish {
18+
return t === null || t === undefined;
19+
}

0 commit comments

Comments
 (0)