Skip to content

Commit

Permalink
feat: enable strict flags (#210)
Browse files Browse the repository at this point in the history
* enable noImplicitAny, add first few fixes

* get it compiling again

* fix lint errors

* Turn on the rest of the strict flags
  • Loading branch information
mmkal committed Oct 20, 2020
1 parent 169c7b9 commit ef2e2de
Show file tree
Hide file tree
Showing 29 changed files with 107 additions and 53 deletions.
13 changes: 12 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
"root": true,
"rules": {
"@typescript-eslint/no-explicit-any": 1,
"@typescript-eslint/no-non-null-assertion": 1,
"linebreak-style": 0,
// https://github.com/typescript-eslint/typescript-eslint/issues/1624#issuecomment-589731039
"import/no-unresolved": 0,
"no-extra-parens": 0,
"no-unused-vars": 0,
"@typescript-eslint/no-unused-vars": 1,
"require-await": 0,
Expand All @@ -39,5 +41,14 @@
"allowTaggedTemplates": true
}
]
}
},
"overrides": [
{
"files": "*.d.ts",
"rules": {
"filenames/match-regex": 0,
"import/unambiguous": 0
}
}
]
}
9 changes: 8 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@
"@babel/plugin-transform-typescript": "^7.12.1",
"@babel/preset-env": "^7.11.5",
"@babel/register": "^7.11.5",
"@types/concat-stream": "^1.6.0",
"@types/pg": "^7.14.5",
"@types/pg-copy-streams": "^1.2.1",
"@types/roarr": "^2.14.2",
"@types/sinon": "^9.0.8",
"@types/through2": "^2.0.36",
"@typescript-eslint/eslint-plugin": "2.26.0",
"@typescript-eslint/parser": "2.26.0",
"ava": "^3.13.0",
Expand Down Expand Up @@ -115,7 +121,8 @@
"build": "rm -fr ./dist && NODE_ENV=production babel ./src --out-dir ./dist --extensions '.ts' --copy-files --source-maps && tsc -p tsconfig.lib.json",
"create-readme": "gitdown ./.README/README.md --output-file ./README.md",
"eslint": "eslint --ext '.ts' --max-warnings 0",
"lint": "npm run eslint ./src ./test && tsc -p .",
"type-check": "tsc -p .",
"lint": "npm run eslint ./src ./test && npm run type-check",
"test": "NODE_ENV=test nyc ava --verbose",
"prepare": "patch-package"
},
Expand Down
2 changes: 1 addition & 1 deletion src/QueryStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export default class QueryStream extends Readable {
}
this._reading = true;
const readAmount = Math.max(size, this.batchSize);
this.cursor.read(readAmount, (error, rows, result) => {
this.cursor.read(readAmount, (error: Error, rows: unknown[], result: any) => {
if (this._closed) {
return;
}
Expand Down
6 changes: 4 additions & 2 deletions src/binders/bindPool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,12 @@ export default (
clientConfiguration,
'IMPLICIT_QUERY',
(connectionLog, connection, boundConnection) => {
return boundConnection[targetMethodName](query);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (boundConnection as any)[targetMethodName](query);
},
(newPool) => {
return newPool[targetMethodName](query);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (newPool as any)[targetMethodName](query);
},
query,
);
Expand Down
2 changes: 1 addition & 1 deletion src/binders/bindTransactionConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default (
clientConfiguration: ClientConfigurationType,
transactionDepth: number,
): DatabaseTransactionConnectionType => {
const mapInvocation = (fn) => {
const mapInvocation = (fn: Parameters<typeof mapTaggedTemplateLiteralInvocation>[0]) => {
const bound = mapTaggedTemplateLiteralInvocation(fn);

return (taggedQuery: TaggedTemplateLiteralInvocationType) => {
Expand Down
4 changes: 2 additions & 2 deletions src/connectionMethods/copyFromBinary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
encodeTupleList,
} from '../utilities';

const bufferToStream = (buffer) => {
const bufferToStream = (buffer: Buffer) => {
const stream = new Duplex();

stream.push(buffer);
Expand Down Expand Up @@ -56,7 +56,7 @@ const copyFromBinary: InternalCopyFromBinaryFunctionType = async (
bufferToStream(payloadBuffer).pipe(copyFromBinaryStream);

return new Promise((resolve, reject) => {
copyFromBinaryStream.on('error', (error) => {
copyFromBinaryStream.on('error', (error: Error) => {
reject(error);
});

Expand Down
11 changes: 7 additions & 4 deletions src/connectionMethods/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

/* eslint-disable promise/prefer-await-to-callbacks */

import type Stream from 'stream';
import through from 'through2';
import QueryStream from '../QueryStream';
import {
Expand All @@ -11,6 +12,7 @@ import {
executeQuery,
} from '../routines';
import type {
InterceptorType,
InternalStreamFunctionType,
} from '../types';

Expand All @@ -29,9 +31,9 @@ const stream: InternalStreamFunctionType = async (connectionLogger, connection,

const query = new QueryStream(finalSql, finalValues);

const queryStream = finalConnection.query(query);
const queryStream: Stream = finalConnection.query(query);

const rowTransformers = [];
const rowTransformers: NonNullable<InterceptorType['transformRow']>[] = [];

for (const interceptor of clientConfiguration.interceptors) {
if (interceptor.transformRow) {
Expand All @@ -40,11 +42,12 @@ const stream: InternalStreamFunctionType = async (connectionLogger, connection,
}

return new Promise((resolve, reject) => {
queryStream.on('error', (error) => {
queryStream.on('error', (error: Error) => {
reject(error);
});

const transformedStream = queryStream.pipe(through.obj(function (datum, enc, callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const transformedStream = queryStream.pipe(through.obj(function (datum: any, enc: any, callback: any) {
let finalRow = datum.row;

if (rowTransformers.length) {
Expand Down
12 changes: 12 additions & 0 deletions src/declarations.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
declare module 'get-stack-trace';
declare module 'pg-cursor';
declare module 'pg-copy-streams-binary';
declare module 'pg/lib/type-overrides' {
const TypeOverrides: {
new(): {
setTypeParser(type: string, parser: (value: string) => unknown): void
}
};

export default TypeOverrides;
}
2 changes: 1 addition & 1 deletion src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import ExtendableError from 'es6-error';

export class SlonikError extends ExtendableError {
originalError: Error
originalError!: Error
}

export class InvalidConfigurationError extends SlonikError {}
Expand Down
6 changes: 4 additions & 2 deletions src/factories/createConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ type ConnectionHandlerType = (

type PoolHandlerType = (pool: DatabasePoolType) => Promise<unknown>;

const terminatePoolConnection = (pool, connection, error) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const terminatePoolConnection = (pool: any, connection: any, error: any) => {
if (!connection.connection.slonik.terminated) {
connection.connection.slonik.terminated = error;
}
Expand All @@ -56,7 +57,8 @@ const createConnection = async (
connectionHandler: ConnectionHandlerType,
poolHandler: PoolHandlerType,
query: TaggedTemplateLiteralInvocationType | null = null,
) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> => {
if (pool.slonik.ended) {
throw new UnexpectedStateError('Connection pool shutdown has been already initiated. Cannot create a new connection.');
}
Expand Down
16 changes: 13 additions & 3 deletions src/factories/createPool.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
// @flow

// eslint-disable-next-line fp/no-events
import type {
EventEmitter,
} from 'events';
import type pgTypes from 'pg';
import {
serializeError,
} from 'serialize-error';
Expand Down Expand Up @@ -47,7 +52,7 @@ export default (
poolLog.debug('pg-native module is not found');
}

let pg;
let pg: typeof pgTypes.native;
let native = false;

if (clientConfiguration.preferNativeBindings && pgNativeBindingsAreAvailable) {
Expand All @@ -69,7 +74,11 @@ export default (
pg = require('pg');
}

const pool = new pg.Pool(poolConfiguration);
type ModifiedPool = Omit<pgTypes.Pool, 'on'> & EventEmitter & {
slonik?: {};
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const pool: ModifiedPool = new pg!.Pool(poolConfiguration as unknown as pgTypes.PoolConfig);

pool.slonik = {
ended: false,
Expand All @@ -89,7 +98,8 @@ export default (
});

// istanbul ignore next
pool.on('connect', (client) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
pool.on('connect', (client: EventEmitter & {connection: any; processID: string}) => {
client.connection = client.connection || {};

client.connection.slonik = {
Expand Down
2 changes: 1 addition & 1 deletion src/factories/typeParsers/createBigintTypeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
TypeParserType,
} from '../../types';

const bigintParser = (value) => {
const bigintParser = (value: string) => {
// @todo Use bigint when value is greater than Number.MAX_SAFE_INTEGER.
return Number.parseInt(value, 10);
};
Expand Down
2 changes: 1 addition & 1 deletion src/factories/typeParsers/createDateTypeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
TypeParserType,
} from '../../types';

const dateParser = (value) => {
const dateParser = (value: string) => {
return value;
};

Expand Down
2 changes: 1 addition & 1 deletion src/factories/typeParsers/createIntervalTypeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type {
TypeParserType,
} from '../../types';

const intervalParser = (value) => {
const intervalParser = (value: string) => {
return value === null ? value : durationToSeconds(parseIsoDuration(parseInterval(value).toISOString()));
};

Expand Down
2 changes: 1 addition & 1 deletion src/factories/typeParsers/createNumericTypeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
TypeParserType,
} from '../../types';

const numericParser = (value) => {
const numericParser = (value: string) => {
return Number.parseFloat(value);
};

Expand Down
2 changes: 1 addition & 1 deletion src/factories/typeParsers/createTimestampTypeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
TypeParserType,
} from '../../types';

const timestampParser = (value) => {
const timestampParser = (value: string | null) => {
return value === null ? value : Date.parse(value);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
TypeParserType,
} from '../../types';

const timestampParser = (value) => {
const timestampParser = (value: string | null) => {
return value === null ? value : Date.parse(value);
};

Expand Down
3 changes: 2 additions & 1 deletion src/routines/createTypeOverrides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ export default async (connection: InternalDatabaseConnectionType, typeParsers: R
return typeParser.name;
});

const postgresTypes = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const postgresTypes: any[] = (
await connection.query('SELECT oid, typarray, typname FROM pg_type WHERE typname = ANY($1::text[])', [
typeNames,
])
Expand Down
18 changes: 12 additions & 6 deletions src/routines/executeQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,28 @@ import type {
ClientConfigurationType,
InternalDatabaseConnectionType,
LoggerType,
NoticeType,
PrimitiveValueExpressionType,
QueryContextType,
QueryIdType,
QueryResultRowType,
QueryResultType,
QueryType,
} from '../types';
import {
createQueryId,
normaliseQueryValues,
} from '../utilities';

type GenericQueryResult = QueryResultType<QueryResultRowType>;

type ExecutionRoutineType = (
connection: InternalDatabaseConnectionType,
sql: string,
values: ReadonlyArray<PrimitiveValueExpressionType>,
queryContext: QueryContextType,
query: QueryType,
) => Promise<unknown>;
) => Promise<GenericQueryResult>;

type TransactionQueryType = {
readonly executionContext: QueryContextType;
Expand All @@ -59,7 +63,7 @@ const retryTransaction = async (
transactionQueries: ReadonlyArray<TransactionQueryType>,
retryLimit: number,
) => {
let result;
let result: GenericQueryResult;
let remainingRetries = retryLimit;
let attempt = 0;

Expand Down Expand Up @@ -103,7 +107,8 @@ const retryTransaction = async (
}
}

return result;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return result!;
};

// eslint-disable-next-line complexity
Expand Down Expand Up @@ -183,7 +188,7 @@ export default async (
}
}

let result;
let result: GenericQueryResult | null;

for (const interceptor of clientConfiguration.interceptors) {
if (interceptor.beforeQueryExecution) {
Expand All @@ -197,9 +202,9 @@ export default async (
}
}

const notices = [];
const notices: NoticeType[] = [];

const noticeListener = (notice) => {
const noticeListener = (notice: NoticeType) => {
notices.push(notice);
};

Expand All @@ -217,6 +222,7 @@ export default async (
});
}

// @ts-expect-error
result = await executionRoutine(
connection,
actualQuery.sql,
Expand Down
1 change: 1 addition & 0 deletions src/sqlFragmentFactories/createUnnestSqlFragment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export default (token: UnnestSqlTokenType, greatestParameterPosition: number): S
throw new InvalidInputError('Invalid unnest tuple member type. Must be a primitive value expression.');
}

// @ts-expect-error
unnestBindings[tupleColumnIndex++].push(tupleValue);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export type FieldType = {
readonly name: string;
};

type NoticeType = {
export type NoticeType = {
readonly code: string;
readonly length: number;
readonly message: string;
Expand Down
2 changes: 1 addition & 1 deletion src/utilities/encodeTupleList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default (
tupleStream
.pipe(encode)
.pipe(concatStream)
.on('error', (error) => {
.on('error', (error: Error) => {
reject(error);
});

Expand Down
Loading

0 comments on commit ef2e2de

Please sign in to comment.