Skip to content

Commit

Permalink
refactor: turn on compilerOptions.strict
Browse files Browse the repository at this point in the history
  • Loading branch information
cyjake committed Oct 31, 2023
1 parent c5bdd50 commit bba6cf6
Show file tree
Hide file tree
Showing 34 changed files with 478 additions and 430 deletions.
118 changes: 3 additions & 115 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,115 +1,3 @@
import DataTypes, { DataType, AbstractDataType, LENGTH_VARIANTS } from './src/data_types';
import {
Hint, IndexHint, HintInterface,
INDEX_HINT_SCOPE_TYPE, INDEX_HINT_SCOPE, INDEX_HINT_TYPE
} from './src/hint';
import {
Literal, Validator,
Connection, QueryOptions, WhereConditions,
Raw, ColumnMeta, AttributeMeta,
BeforeHooksType, AfterHooksType, Collection,
GeneratorReturnType, Values, BoneCreateValues, BoneInstanceValues,
} from './src/types/common';
import { SpellMeta, Spell, SpellBookFormatResult } from './src/spell';
import Bone from './src/bone';
import { ConnectOptions, AbstractDriver } from './src/drivers';

export {
LENGTH_VARIANTS as LENGTH_VARIANTS,
DataTypes, Literal, Validator, Connection, WhereConditions,
Hint, IndexHint, HintInterface, INDEX_HINT_SCOPE_TYPE, INDEX_HINT_SCOPE, INDEX_HINT_TYPE,
Bone, Raw, Collection,
SpellMeta, Spell, ColumnMeta, AttributeMeta, SpellBookFormatResult, Values, BoneCreateValues, BoneInstanceValues,
};

export * from './src/decorators';
export * from './src/drivers';
export * from './src/adapters/sequelize';

interface InitOptions {
underscored?: boolean;
tableName?: string;
hooks?: {
[key in BeforeHooksType ]: (options: QueryOptions) => Promise<void>
} | {
[key in AfterHooksType ]: (instance: Bone, result: object) => Promise<void>
};
}

interface SyncOptions {
force?: boolean;
alter?: boolean;
}

interface RawQueryOptions {
replacements?: { [key:string]: Literal | Literal[] };
connection?: Connection;
}

export default class Realm {
Bone: typeof Bone;
DataTypes: typeof DataTypes;
driver: AbstractDriver;
models: Record<string, typeof Bone>;
connected?: boolean;
options: ConnectOptions;

constructor(options: ConnectOptions);

connect(): Promise<Bone>;

/**
* disconnect manually
* @param callback
*/
disconnect(callback?: () => Promise<void>): Promise<boolean | void>;

define(
name: string,
attributes: Record<string, AbstractDataType<DataType> | AttributeMeta>,
options?: InitOptions,
descriptors?: Record<string, PropertyDescriptor>,
): typeof Bone;

raw(sql: string): Raw;

escape(value: Literal): string;

query<T>(sql: string, values?: Array<Literal>, options?: RawQueryOptions & { model?: T }): Promise<{ rows: T extends typeof Bone ? InstanceType<T>[] : Record<string, Literal>[], fields?: Record<string, ColumnMeta>[], affectedRows?: number }>;

transaction<T extends (options: { connection: Connection }) => Generator>(callback: T): Promise<GeneratorReturnType<ReturnType<T>>>;
transaction<T extends (options: { connection: Connection }) => Promise<any>>(callback: T): Promise<ReturnType<T>>;

sync(options?: SyncOptions): Promise<void>;
}

/**
* Connect models to database.
* @example
* connect({
* host: 'localhost',
* user: 'root',
* database: 'leoric',
* models: path.join(__dirname, 'models')
* })
*/
export function connect(opts: ConnectOptions): Promise<Realm>;
export function disconnect(realm: Realm, callback?: () => Promise<void>): Promise<boolean | void>;

/**
* Check if cls is subclass of Bone
* @param cls
*/
export function isBone(cls: any): boolean;

/**
* Concatenate multiline SQL into oneline
* @example
* heresql(`
* SELECT *
* FROM users
* WHERE age >= 35
* `)
* @param text
*/
export function heresql(text): string;
import Realm from './src';
export default Realm;
export * from './src';
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@
"name": "leoric",
"version": "2.11.4",
"description": "JavaScript Object-relational mapping alchemy",
"main": "index.js",
"main": "dist/index.js",
"browser": "dist/browser.js",
"types": "index.d.ts",
"files": [
"dist",
"src",
"index.js",
"index.d.ts"
],
Expand Down Expand Up @@ -101,25 +100,28 @@
"@babel/eslint-parser": "^7.14.7",
"@cara/minami": "^1.2.3",
"@journeyapps/sqlcipher": "^5.2.0",
"@tsconfig/node16": "^16.1.1",
"@types/mocha": "^9.0.0",
"@types/node": "^16.10.1",
"@types/sinon": "^10.0.20",
"@types/sql.js": "^1.4.4",
"@typescript-eslint/eslint-plugin": "^5.59.2",
"@typescript-eslint/parser": "^5.59.2",
"eslint": "^7.20.0",
"eslint": "^8.52.0",
"eslint-plugin-no-only-tests": "^3.0.0",
"expect.js": "^0.3.1",
"husky": "^8.0.3",
"jsdoc": "^3.6.3",
"lint-staged": "^13.2.2",
"mocha": "^8.2.1",
"mocha": "^10.2.0",
"mysql": "^2.17.1",
"mysql2": "^2.3.0",
"nyc": "^15.1.0",
"pg": "^8.5.1",
"sinon": "^10.0.0",
"sql.js": "^1.8.0",
"sqlite3": "^5.0.2",
"ts-node": "^10.9.1",
"typescript": "^4.6.2"
}
}
9 changes: 7 additions & 2 deletions src/adapters/sequelize.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ module.exports = function sequelize(Bone) {
* @protect
* store all configured scopes
*/
static _scopes = {}
static _scopes = {};
// scope
static _scope = null;

Expand Down Expand Up @@ -159,14 +159,19 @@ module.exports = function sequelize(Bone) {
const parentTable = this.table;
const parent = this;
class ScopeClass extends this {
static name = parentName;
static get synchronized() {
return parent.synchronized;
}
static get table() {
return parentTable;
}
}
Object.defineProperty(ScopeClass, 'name', {
value: parentName,
writable: false,
enumerable: false,
configurable: true,
});

ScopeClass.setScope(name, ...args);
return ScopeClass;
Expand Down
6 changes: 4 additions & 2 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const Realm = require('./realm/base');
const AbstractDriver = require('./drivers/abstract');
const { isBone } = require('./utils');

import { ConnectOptions } from './drivers';

/**
* @typedef {Object} RawSql
* @property {boolean} __raw
Expand All @@ -25,15 +27,15 @@ const { isBone } = require('./utils');
* @param {string|Bone[]} opts.models - an array of models
* @returns {Pool} the connection pool in case we need to perform raw query
*/
export const connect = async function connect(opts) {
export const connect = async function connect(opts: ConnectOptions & { Bone?: typeof Bone }): Promise<InstanceType<typeof Realm>> {
opts = { Bone, ...opts };
if (opts.Bone.driver) throw new Error('connected already');
const realm = new Realm(opts);
await realm.connect();
return realm;
};

export const disconnect = async function disconnect(realm, ...args) {
export const disconnect = async function disconnect(realm: InstanceType<typeof Realm>, ...args: unknown[]) {
if (realm instanceof Realm && realm.connected) {
return await realm.disconnect(...args);
}
Expand Down
37 changes: 20 additions & 17 deletions src/data_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export enum LENGTH_VARIANTS {
empty = '',
medium = 'medium',
long = 'long',
};
}

export interface AbstractDataType<T> {
new (dataLength?: LENGTH_VARIANTS | number): DataType & T;
Expand All @@ -24,7 +24,7 @@ export interface AbstractDataType<T> {
*/

export abstract class DataType {
dataType: string = '';
dataType = '';
dataLength?: string | number;

/**
Expand Down Expand Up @@ -59,7 +59,7 @@ function hasDataLength(dataLength: string | number | undefined) {
* @param {number} dataLength
*/
class STRING extends DataType {
constructor(dataLength: number = 255) {
constructor(dataLength = 255) {
super();
this.dataType = 'varchar';
this.dataLength = dataLength;
Expand Down Expand Up @@ -90,7 +90,7 @@ class STRING extends DataType {
}

class CHAR extends STRING {
constructor(dataLength: number = 255) {
constructor(dataLength = 255) {
super(dataLength);
this.dataType = 'char';
}
Expand Down Expand Up @@ -289,7 +289,7 @@ class DATE extends DataType {
precision?: number | null;
timezone?: boolean = true;

constructor(precision?: number | null, timezone: boolean = true) {
constructor(precision?: number | null, timezone = true) {
super();
this.dataType = 'datetime';
this.precision = precision;
Expand All @@ -305,7 +305,7 @@ class DATE extends DataType {
return dataType;
}

_round(value) {
_round(value: Date) {
const { precision } = this;
if (precision != null && precision < 3 && value instanceof Date) {
const divider = 10 ** (3 - precision);
Expand Down Expand Up @@ -359,7 +359,7 @@ class DATEONLY extends DATE {
return this.dataType.toUpperCase();
}

_round(value) {
_round(value: Date) {
if (value instanceof Date) {
return new Date(value.getFullYear(), value.getMonth(), value.getDate());
}
Expand All @@ -377,7 +377,7 @@ class BOOLEAN extends DataType {
return this.dataType.toUpperCase();
}

cast(value) {
cast(value: boolean) {
if (value == null) return value;
return Boolean(value);
}
Expand Down Expand Up @@ -412,7 +412,7 @@ class BLOB extends DataType {
return [ this.dataLength, this.dataType ].join('').toUpperCase();
}

cast(value) {
cast(value: Buffer | string) {
if (value == null) return value;
if (Buffer.isBuffer(value)) return value;
return Buffer.from(value);
Expand All @@ -434,7 +434,7 @@ class MYJSON extends DataType {
return 'TEXT';
}

cast(value) {
cast(value: null | object | string) {
if (!value) return value;
// type === JSONB
if (typeof value === 'object') return value;
Expand All @@ -446,7 +446,7 @@ class MYJSON extends DataType {
}
}

uncast(value) {
uncast(value: null | Raw | object) {
if (value == null || value instanceof Raw) return value;
return global.JSON.stringify(value);
}
Expand All @@ -471,7 +471,8 @@ class JSONB extends MYJSON {
}

class VIRTUAL extends DataType {
virtual: boolean = true;
virtual = true;

constructor() {
super();
this.dataType = 'virtual';
Expand Down Expand Up @@ -532,23 +533,25 @@ class DataTypes {
static BOOLEAN: DATA_TYPE<BOOLEAN> = BOOLEAN as any;

static findType(columnType: string): DataTypes {
/* eslint-disable @typescript-eslint/no-shadow */
const {
CHAR, STRING, TEXT, DATE, DATEONLY,
TINYINT, SMALLINT, MEDIUMINT, INTEGER,
TINYINT, SMALLINT, MEDIUMINT, INTEGER,
BIGINT, DECIMAL, BOOLEAN,
BINARY, VARBINARY, BLOB,
} = this;
/* eslint-enable @typescript-eslint/no-shadow */

const res = columnType?.match(/(\w+)(?:\((\d+)(?:,(\d+))?\))?/);
if(!res) {
if (!res) {
throw new Error(`Unknown columnType ${columnType}`);
}
const [ , dataType, ...matches ] = res;
const params: any[] = [];
for (let i = 0; i < matches.length; i++) {
if (matches[i] != null) params[i] = parseInt(matches[i], 10);
}

switch (dataType) {
case 'char':
return new CHAR(...params);
Expand Down Expand Up @@ -608,12 +611,12 @@ class DataTypes {

static get invokable() {
return new Proxy(this, {
get(target, p) {
get(target, p: keyof DataTypes) {
const value = target[p];
if (AllDataTypes.hasOwnProperty(p)) return invokableFunc(value);
return value;
}
});
});
}

/**
Expand Down
Loading

0 comments on commit bba6cf6

Please sign in to comment.