Skip to content

Commit

Permalink
Improve ESLint config and fix its errors
Browse files Browse the repository at this point in the history
  • Loading branch information
dankochetov committed Apr 18, 2023
1 parent ae6d323 commit b4cebd9
Show file tree
Hide file tree
Showing 115 changed files with 1,375 additions and 1,019 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
dist
examples
38 changes: 37 additions & 1 deletion .eslintrc.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
root: true
extends:
- 'plugin:@typescript-eslint/base'
- 'eslint:recommended'
- 'plugin:@typescript-eslint/recommended'
- 'plugin:unicorn/recommended'
parser: '@typescript-eslint/parser'
plugins:
- import
Expand All @@ -17,3 +19,37 @@ rules:
import/no-useless-path-segments: error
import/newline-after-import: error
import/no-duplicates: error
'@typescript-eslint/no-explicit-any': 'off'
'@typescript-eslint/no-non-null-assertion': 'off'
'@typescript-eslint/no-namespace': 'off'
'@typescript-eslint/no-unused-vars':
- error
- argsIgnorePattern: '^_'
varsIgnorePattern: '^_'
'@typescript-eslint/ban-types':
- error
- extendDefaults: true
types:
'{}' : false
'@typescript-eslint/no-this-alias': 'off'
'@typescript-eslint/no-var-requires': 'off'
'unicorn/prefer-node-protocol': 'off'
'unicorn/prefer-top-level-await': 'off'
'unicorn/prevent-abbreviations': 'off'
'unicorn/prefer-switch': 'off'
'unicorn/catch-error-name': 'off'
'unicorn/no-null': 'off'
'unicorn/numeric-separators-style': 'off'
'unicorn/explicit-length-check': 'off'
'unicorn/filename-case': 'off'
'unicorn/prefer-module': 'off'
'unicorn/no-array-reduce': 'off'
'unicorn/no-nested-ternary': 'off'
'unicorn/no-useless-undefined':
- error
- checkArguments: false
'unicorn/no-this-assignment': 'off'
'unicorn/empty-brace-spaces': 'off'
'unicorn/no-thenable': 'off'
'unicorn/consistent-function-scoping': 'off'
'unicorn/prefer-type-error': 'off'
4 changes: 2 additions & 2 deletions drizzle-orm/src/alias.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { type View, ViewBaseConfig } from './view';
export class ColumnAliasProxyHandler<TColumn extends AnyColumn> implements ProxyHandler<TColumn> {
constructor(private table: Table | View) {}

get(columnObj: TColumn, prop: string | symbol, receiver: any): any {
get(columnObj: TColumn, prop: string | symbol): any {
if (prop === 'table') {
return this.table;
}
Expand All @@ -18,7 +18,7 @@ export class ColumnAliasProxyHandler<TColumn extends AnyColumn> implements Proxy
export class TableAliasProxyHandler<T extends Table | View> implements ProxyHandler<T> {
constructor(private alias: string, private replaceOriginalName: boolean) {}

get(tableObj: T, prop: string | symbol, receiver: any): any {
get(tableObj: T, prop: string | symbol): any {
if (prop === Table.Symbol.Name) {
return this.alias;
}
Expand Down
35 changes: 17 additions & 18 deletions drizzle-orm/src/aws-data-api/common/index.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
import type { Field} from '@aws-sdk/client-rds-data';
import type { Field } from '@aws-sdk/client-rds-data';
import { TypeHint } from '@aws-sdk/client-rds-data';
import type { QueryTypingsValue } from '~/sql';

export function getValueFromDataApi(row: Field) {
if (typeof row.stringValue !== 'undefined') {
if (row.stringValue !== undefined) {
return row.stringValue;
} else if (typeof row.booleanValue !== 'undefined') {
} else if (row.booleanValue !== undefined) {
return row.booleanValue;
} else if (typeof row.doubleValue !== 'undefined') {
} else if (row.doubleValue !== undefined) {
return row.doubleValue;
} else if (typeof row.isNull !== 'undefined') {
} else if (row.isNull !== undefined) {
return null;
} else if (typeof row.longValue !== 'undefined') {
} else if (row.longValue !== undefined) {
return row.longValue;
} else if (typeof row.blobValue !== 'undefined') {
} else if (row.blobValue !== undefined) {
return row.blobValue;
} else if (typeof row.arrayValue !== 'undefined') {
if (typeof row.arrayValue.stringValues !== 'undefined') {
// eslint-disable-next-line unicorn/no-negated-condition
} else if (row.arrayValue !== undefined) {
if (row.arrayValue.stringValues !== undefined) {
return row.arrayValue.stringValues;
}
throw Error('Unknown array type');
throw new Error('Unknown array type');
} else {
throw Error('Unknown type');
throw new Error('Unknown type');
}
}

Expand All @@ -44,19 +45,17 @@ export function typingsToAwsTypeHint(typings?: QueryTypingsValue): TypeHint | un
}

export function toValueParam(value: any, typings?: QueryTypingsValue): { value: Field; typeHint?: TypeHint } {
let response: { value: Field; typeHint?: TypeHint } = {
const response: { value: Field; typeHint?: TypeHint } = {
value: {} as any,
typeHint: typingsToAwsTypeHint(typings),
};

if (value === null) {
response.value = { isNull: true };
} else if (typeof value === 'string') {
if (response.typeHint === 'DATE') {
response.value = { stringValue: value.split('T')[0]! };
} else {
response.value = { stringValue: value };
}
response.value = response.typeHint === 'DATE'
? { stringValue: value.split('T')[0]! }
: { stringValue: value };
} else if (typeof value === 'number' && Number.isInteger(value)) {
response.value = { longValue: value };
} else if (typeof value === 'number' && !Number.isInteger(value)) {
Expand All @@ -66,7 +65,7 @@ export function toValueParam(value: any, typings?: QueryTypingsValue): { value:
} else if (value instanceof Date) {
response.value = { stringValue: value.toISOString().replace('T', ' ').replace('Z', '') };
} else {
throw Error(`Unknown type for ${value}`);
throw new Error(`Unknown type for ${value}`);
}

return response;
Expand Down
10 changes: 5 additions & 5 deletions drizzle-orm/src/aws-data-api/pg/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,21 +56,21 @@ export class AwsDataApiPreparedQuery<T extends PreparedQueryConfig> extends Prep

this.options.logger?.logQuery(this.rawQuery.input.sql!, this.rawQuery.input.parameters);

const { fields } = this;
const { fields, rawQuery, client, joinsNotNullableMap } = this;
if (!fields) {
return await this.client.send(this.rawQuery);
return await client.send(rawQuery);
}

const result = await this.client.send(this.rawQuery);
const result = await client.send(rawQuery);

return result.records?.map((result: any) => {
const mappedResult = result.map((res: any) => getValueFromDataApi(res));
return mapResultRow<T['execute']>(fields, mappedResult, this.joinsNotNullableMap);
return mapResultRow<T['execute']>(fields, mappedResult, joinsNotNullableMap);
});
}

all(placeholderValues?: Record<string, unknown> | undefined): Promise<T['all']> {
return this.execute(placeholderValues)
return this.execute(placeholderValues);
}
}

Expand Down
16 changes: 8 additions & 8 deletions drizzle-orm/src/better-sqlite3/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,32 +78,32 @@ export class PreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig>
}

all(placeholderValues?: Record<string, unknown>): T['all'] {
const { fields } = this;
const { fields, joinsNotNullableMap, queryString, logger, stmt } = this;
if (fields) {
return this.values(placeholderValues).map((row) => mapResultRow(fields, row, this.joinsNotNullableMap));
return this.values(placeholderValues).map((row) => mapResultRow(fields, row, joinsNotNullableMap));
}

const params = fillPlaceholders(this.params, placeholderValues ?? {});
this.logger.logQuery(this.queryString, params);
return this.stmt.all(...params);
logger.logQuery(queryString, params);
return stmt.all(...params);
}

get(placeholderValues?: Record<string, unknown>): T['get'] {
const params = fillPlaceholders(this.params, placeholderValues ?? {});
this.logger.logQuery(this.queryString, params);

const { fields } = this;
const { fields, stmt, joinsNotNullableMap } = this;
if (!fields) {
return this.stmt.get(...params);
return stmt.get(...params);
}

const value = this.stmt.raw().get(...params);
const value = stmt.raw().get(...params);

if (!value) {
return undefined;
}

return mapResultRow(fields, value, this.joinsNotNullableMap);
return mapResultRow(fields, value, joinsNotNullableMap);
}

values(placeholderValues?: Record<string, unknown>): T['values'] {
Expand Down
12 changes: 6 additions & 6 deletions drizzle-orm/src/bun-sqlite/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,14 @@ export class PreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig>
}

all(placeholderValues?: Record<string, unknown>): T['all'] {
const { fields } = this;
const { fields, queryString, logger, joinsNotNullableMap, stmt } = this;
if (fields) {
return this.values(placeholderValues).map((row) => mapResultRow(fields, row, this.joinsNotNullableMap));
return this.values(placeholderValues).map((row) => mapResultRow(fields, row, joinsNotNullableMap));
}

const params = fillPlaceholders(this.params, placeholderValues ?? {});
this.logger.logQuery(this.queryString, params);
return this.stmt.all(...params);
logger.logQuery(queryString, params);
return stmt.all(...params);
}

get(placeholderValues?: Record<string, unknown>): T['get'] {
Expand All @@ -108,12 +108,12 @@ export class PreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig>
return undefined;
}

const { fields } = this;
const { fields, joinsNotNullableMap } = this;
if (!fields) {
return value;
}

return mapResultRow(fields, value, this.joinsNotNullableMap);
return mapResultRow(fields, value, joinsNotNullableMap);
}

values(placeholderValues?: Record<string, unknown>): T['values'] {
Expand Down
8 changes: 4 additions & 4 deletions drizzle-orm/src/d1/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,16 +90,16 @@ export class PreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig>
}

all(placeholderValues?: Record<string, unknown>): Promise<T['all']> {
const { fields } = this;
const { fields, joinsNotNullableMap, queryString, logger, stmt } = this;
if (fields) {
return this.values(placeholderValues).then((values) =>
values.map((row) => mapResultRow(fields, row, this.joinsNotNullableMap))
values.map((row) => mapResultRow(fields, row, joinsNotNullableMap))
);
}

const params = fillPlaceholders(this.params, placeholderValues ?? {});
this.logger.logQuery(this.queryString, params);
return this.stmt.bind(...params).all().then(({ results }) => results!);
logger.logQuery(queryString, params);
return stmt.bind(...params).all().then(({ results }) => results!);
}

get(placeholderValues?: Record<string, unknown>): Promise<T['get']> {
Expand Down
8 changes: 3 additions & 5 deletions drizzle-orm/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ export class DrizzleError extends Error {
}

static wrap(error: unknown, message?: string): DrizzleError {
if (error instanceof Error) {
return new DrizzleError(message ? `${message}: ${error.message}` : error.message, { cause: error });
} else {
return new DrizzleError(message ?? String(error));
}
return error instanceof Error
? new DrizzleError(message ? `${message}: ${error.message}` : error.message, { cause: error })
: new DrizzleError(message ?? String(error));
}
}

Expand Down
16 changes: 8 additions & 8 deletions drizzle-orm/src/libsql/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export class LibSQLSession extends SQLiteSession<'async', ResultSet> {

override async transaction<T>(
transaction: (db: LibSQLTransaction) => T | Promise<T>,
config?: SQLiteTransactionConfig,
_config?: SQLiteTransactionConfig,
): Promise<T> {
// TODO: support transaction behavior
const libsqlTx = await this.client.transaction();
Expand Down Expand Up @@ -103,25 +103,25 @@ export class PreparedQuery<T extends PreparedQueryConfig = PreparedQueryConfig>
}

all(placeholderValues?: Record<string, unknown>): Promise<T['all']> {
const { fields } = this;
const { fields, joinsNotNullableMap, logger, queryString, tx, client } = this;
if (fields) {
const values = this.values(placeholderValues);

return values.then((rows) =>
rows.map((row) => {
return mapResultRow(
fields,
Array.prototype.slice.call(row).map(normalizeFieldValue),
this.joinsNotNullableMap,
Array.prototype.slice.call(row).map((v) => normalizeFieldValue(v)),
joinsNotNullableMap,
);
})
);
}

const params = fillPlaceholders(this.params, placeholderValues ?? {});
this.logger.logQuery(this.queryString, params);
const stmt: InStatement = { sql: this.queryString, args: params as InArgs };
return (this.tx ? this.tx.execute(stmt) : this.client.execute(stmt)).then(({ rows }) => rows.map(normalizeRow));
logger.logQuery(queryString, params);
const stmt: InStatement = { sql: queryString, args: params as InArgs };
return (tx ? tx.execute(stmt) : client.execute(stmt)).then(({ rows }) => rows.map((row) => normalizeRow(row)));
}

get(placeholderValues?: Record<string, unknown>): Promise<T['get']> {
Expand All @@ -144,7 +144,7 @@ function normalizeRow(obj: any) {
// turn them into objects what's what other SQLite drivers
// do.
return Object.keys(obj).reduce((acc: Record<string, any>, key) => {
if (obj.propertyIsEnumerable(key)) {
if (Object.prototype.propertyIsEnumerable.call(obj, key)) {
acc[key] = obj[key];
}
return acc;
Expand Down
10 changes: 6 additions & 4 deletions drizzle-orm/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ export class ConsoleLogWriter implements LogWriter {
export class DefaultLogger implements Logger {
readonly writer: LogWriter;

constructor(config: { writer: LogWriter } = { writer: new ConsoleLogWriter() }) {
this.writer = config.writer;
constructor(config?: { writer: LogWriter }) {
this.writer = config?.writer ?? new ConsoleLogWriter();
}

logQuery(query: string, params: unknown[]): void {
const stringifiedParams = params.map((p) => {
try {
return JSON.stringify(p);
} catch (e) {
} catch {
return String(p);
}
});
Expand All @@ -33,5 +33,7 @@ export class DefaultLogger implements Logger {
}

export class NoopLogger implements Logger {
logQuery(): void {}
logQuery(): void {
// noop
}
}
8 changes: 4 additions & 4 deletions drizzle-orm/src/migrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ export function readMigrationFiles(config: string | MigrationConfig): MigrationM
}

if (!migrationFolderTo) {
throw Error('no migration folder defined');
throw new Error('no migration folder defined');
}

const migrationQueries: MigrationMeta[] = [];

const journalPath = `${migrationFolderTo}/meta/_journal.json`;
if (!fs.existsSync(journalPath)) {
throw Error(`Can't find meta/_journal.json file`);
throw new Error(`Can't find meta/_journal.json file`);
}

const journalAsString = fs.readFileSync(`${migrationFolderTo}/meta/_journal.json`).toString();
Expand All @@ -62,8 +62,8 @@ export function readMigrationFiles(config: string | MigrationConfig): MigrationM
folderMillis: journalEntry.when,
hash: crypto.createHash('sha256').update(query).digest('hex'),
});
} catch (e) {
throw Error(`No file ${migrationPath} found in ${migrationFolderTo} folder`);
} catch {
throw new Error(`No file ${migrationPath} found in ${migrationFolderTo} folder`);
}
}

Expand Down
Loading

0 comments on commit b4cebd9

Please sign in to comment.