From 8d32e64489baaea053d09d64a378fa19b7331ecb Mon Sep 17 00:00:00 2001 From: Enok <416828041@qq.com> Date: Sat, 16 May 2020 09:53:38 +0800 Subject: [PATCH] upgrade to deno 1.0 --- .travis.yml | 2 +- README.md | 4 +- deps.ts | 12 +-- mod.ts | 12 ++- src/Reflect.ts | 229 +++++++++++++++++++++++---------------------- src/dso.ts | 6 +- src/field.ts | 4 +- src/model.ts | 36 +++---- src/sync.ts | 6 +- src/transaction.ts | 4 +- src/util.ts | 2 +- test.ts | 27 +++--- test/model.ts | 40 ++++---- util.ts | 10 +- 14 files changed, 205 insertions(+), 189 deletions(-) diff --git a/.travis.yml b/.travis.yml index e211538..e6a6c98 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,4 +6,4 @@ before_install: - export PATH="/home/travis/.deno/bin:$PATH" script: - - deno -A -c tsconfig.json ./test.ts + - deno test --unstable --allow-net -c tsconfig.json test.ts diff --git a/README.md b/README.md index 0dc526f..4700715 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![Build Status](https://www.travis-ci.org/manyuanrong/dso.svg?branch=master)](https://www.travis-ci.org/manyuanrong/dso) ![GitHub](https://img.shields.io/github/license/manyuanrong/dso.svg) ![GitHub release](https://img.shields.io/github/release/manyuanrong/dso.svg) -![(Deno)](https://img.shields.io/badge/deno-0.24.0-green.svg) +![(Deno)](https://img.shields.io/badge/deno-1.0.0-green.svg) `dso` is a simple ORM Library based on [deno_mysql](https://github.com/manyuanrong/deno_mysql) @@ -19,7 +19,7 @@ import { Join, Model, Where -} from "https://deno.land/x/dso@0.5.0/mod.ts"; +} from "https://deno.land/x/dso@v1.0.0/mod.ts"; // Define a database model @Model("users") diff --git a/deps.ts b/deps.ts index 70497e1..fcc1773 100644 --- a/deps.ts +++ b/deps.ts @@ -1,19 +1,19 @@ export { assert, assertEquals, - assertThrowsAsync -} from "https://deno.land/std@v0.35.0/testing/asserts.ts"; + assertThrowsAsync, +} from "https://deno.land/std@v0.51.0/testing/asserts.ts"; export { Client, ClientConfig, - Connection -} from "https://deno.land/x/mysql@1.5.0/mod.ts"; + Connection, +} from "https://deno.land/x/mysql@2.1.0/mod.ts"; export { Join, Order, Query, replaceParams, - Where -} from "https://deno.land/x/sql_builder@1.4.0/mod.ts"; + Where, +} from "https://deno.land/x/sql_builder@1.5.0/mod.ts"; import "./src/Reflect.ts"; diff --git a/mod.ts b/mod.ts index 666df77..79fd24b 100644 --- a/mod.ts +++ b/mod.ts @@ -1,5 +1,13 @@ -export { Client, ClientConfig, Join, Order, Query, replaceParams, Where } from "./deps.ts"; +export { + Client, + ClientConfig, + Join, + Order, + Query, + replaceParams, + Where, +} from "./deps.ts"; export { dso } from "./src/dso.ts"; export * from "./src/field.ts"; export * from "./src/model.ts"; -export * from "./src/util.ts"; \ No newline at end of file +export * from "./src/util.ts"; diff --git a/src/Reflect.ts b/src/Reflect.ts index 2bd6fcf..2f77c2b 100644 --- a/src/Reflect.ts +++ b/src/Reflect.ts @@ -92,15 +92,17 @@ namespace Reflect { type MemberDecorator = ( target: Object, propertyKey: string | symbol, - descriptor?: TypedPropertyDescriptor + descriptor?: TypedPropertyDescriptor, ) => TypedPropertyDescriptor | void; declare const Symbol: { iterator: symbol; toPrimitive: symbol }; declare const Set: SetConstructor; declare const WeakMap: WeakMapConstructor; declare const Map: MapConstructor; declare const global: any; + // @ts-ignore declare const crypto: Crypto; + // @ts-ignore declare const msCrypto: Crypto; declare const process: any; @@ -121,7 +123,7 @@ namespace Reflect { */ export declare function decorate( decorators: ClassDecorator[], - target: Function + target: Function, ): Function; /** @@ -163,7 +165,7 @@ namespace Reflect { decorators: (PropertyDecorator | MethodDecorator)[], target: any, propertyKey: string | symbol, - attributes?: PropertyDescriptor | null + attributes?: PropertyDescriptor | null, ): PropertyDescriptor | undefined; /** @@ -205,7 +207,7 @@ namespace Reflect { decorators: (PropertyDecorator | MethodDecorator)[], target: any, propertyKey: string | symbol, - attributes: PropertyDescriptor + attributes: PropertyDescriptor, ): PropertyDescriptor; /** @@ -250,7 +252,7 @@ namespace Reflect { */ export declare function metadata( metadataKey: any, - metadataValue: any + metadataValue: any, ): { (target: Function): void; (target: any, propertyKey: string | symbol): void; @@ -278,7 +280,7 @@ namespace Reflect { export declare function defineMetadata( metadataKey: any, metadataValue: any, - target: any + target: any, ): void; /** @@ -320,7 +322,7 @@ namespace Reflect { metadataKey: any, metadataValue: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): void; /** @@ -372,7 +374,7 @@ namespace Reflect { export declare function hasMetadata( metadataKey: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): boolean; /** @@ -391,7 +393,7 @@ namespace Reflect { */ export declare function hasOwnMetadata( metadataKey: any, - target: any + target: any, ): boolean; /** @@ -427,7 +429,7 @@ namespace Reflect { export declare function hasOwnMetadata( metadataKey: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): boolean; /** @@ -479,7 +481,7 @@ namespace Reflect { export declare function getMetadata( metadataKey: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): any; /** @@ -531,7 +533,7 @@ namespace Reflect { export declare function getOwnMetadata( metadataKey: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): any; /** @@ -580,7 +582,7 @@ namespace Reflect { */ export declare function getMetadataKeys( target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): any[]; /** @@ -629,7 +631,7 @@ namespace Reflect { */ export declare function getOwnMetadataKeys( target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): any[]; /** @@ -648,7 +650,7 @@ namespace Reflect { */ export declare function deleteMetadata( metadataKey: any, - target: any + target: any, ): boolean; /** @@ -684,27 +686,26 @@ namespace Reflect { export declare function deleteMetadata( metadataKey: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): boolean; - (function( + (function ( this: any, factory: ( exporter: ( key: K, - value: typeof Reflect[K] - ) => void - ) => void + value: typeof Reflect[K], + ) => void, + ) => void, ) { var self; - const root = - typeof global === "object" - ? global - : typeof self === "object" - ? self - : typeof this === "object" - ? this - : Function("return this;")(); + const root = typeof global === "object" + ? global + : typeof self === "object" + ? self + : typeof this === "object" + ? this + : Function("return this;")(); let exporter = makeExporter(Reflect); if (typeof root.Reflect === "undefined") { @@ -719,24 +720,24 @@ namespace Reflect { target: typeof Reflect, previous?: ( key: K, - value: typeof Reflect[K] - ) => void + value: typeof Reflect[K], + ) => void, ) { return ( key: K, - value: typeof Reflect[K] + value: typeof Reflect[K], ) => { if (typeof target[key] !== "function") { Object.defineProperty(target, key, { configurable: true, writable: true, - value + value, }); } if (previous) previous(key, value); }; } - })(function(exporter) { + })(function (exporter) { const hasOwn = Object.prototype.hasOwnProperty; // feature test for Symbol support @@ -763,34 +764,31 @@ namespace Reflect { has: downLevel ? (map: HashMap, key: string | number | symbol) => - hasOwn.call(map, key) + hasOwn.call(map, key) : (map: HashMap, key: string | number | symbol) => key in map, get: downLevel ? (map: HashMap, key: string | number | symbol): V | undefined => - hasOwn.call(map, key) ? map[key as string | number] : undefined + hasOwn.call(map, key) ? map[key as string | number] : undefined : (map: HashMap, key: string | number | symbol): V | undefined => - map[key as string | number] + map[key as string | number], }; // Load global or shim versions of Map, Set, and WeakMap const functionPrototype = Object.getPrototypeOf(Function); - const usePolyfill = - typeof process === "object" && + const usePolyfill = typeof process === "object" && process.env && process.env["REFLECT_METADATA_USE_MAP_POLYFILL"] === "true"; - const _Map: typeof Map = - !usePolyfill && + const _Map: typeof Map = !usePolyfill && typeof Map === "function" && typeof Map.prototype.entries === "function" - ? Map - : CreateMapPolyfill(); - const _Set: typeof Set = - !usePolyfill && + ? Map + : CreateMapPolyfill(); + const _Set: typeof Set = !usePolyfill && typeof Set === "function" && typeof Set.prototype.entries === "function" - ? Set - : CreateSetPolyfill(); + ? Set + : CreateSetPolyfill(); const _WeakMap: typeof WeakMap = !usePolyfill && typeof WeakMap === "function" ? WeakMap @@ -808,13 +806,13 @@ namespace Reflect { decorators: (PropertyDecorator | MethodDecorator)[], target: any, propertyKey: string | symbol, - attributes?: PropertyDescriptor | null + attributes?: PropertyDescriptor | null, ): PropertyDescriptor | undefined; function decorate( decorators: (PropertyDecorator | MethodDecorator)[], target: any, propertyKey: string | symbol, - attributes: PropertyDescriptor + attributes: PropertyDescriptor, ): PropertyDescriptor; /** @@ -860,7 +858,7 @@ namespace Reflect { decorators: (ClassDecorator | MemberDecorator)[], target: any, propertyKey?: string | symbol, - attributes?: PropertyDescriptor | null + attributes?: PropertyDescriptor | null, ): PropertyDescriptor | Function | undefined { if (!IsUndefined(propertyKey)) { if (!IsArray(decorators)) throw new TypeError(); @@ -869,22 +867,23 @@ namespace Reflect { !IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes) - ) + ) { throw new TypeError(); + } if (IsNull(attributes)) attributes = undefined; propertyKey = ToPropertyKey(propertyKey); return DecorateProperty( - decorators, + decorators, target, propertyKey, - attributes + attributes, ); } else { if (!IsArray(decorators)) throw new TypeError(); if (!IsConstructor(target)) throw new TypeError(); return DecorateConstructor( - decorators, - target + decorators, + target, ); } } @@ -939,13 +938,14 @@ namespace Reflect { function decorator(target: any, propertyKey: string | symbol): void; function decorator(target: any, propertyKey?: string | symbol): void { if (!IsObject(target)) throw new TypeError(); - if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey)) + if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey)) { throw new TypeError(); + } OrdinaryDefineOwnMetadata( metadataKey, metadataValue, target, - propertyKey + propertyKey, ); } return decorator; @@ -959,13 +959,13 @@ namespace Reflect { function defineMetadata( metadataKey: any, metadataValue: any, - target: any + target: any, ): void; function defineMetadata( metadataKey: any, metadataValue: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): void; /** @@ -1011,7 +1011,7 @@ namespace Reflect { metadataKey: any, metadataValue: any, target: any, - propertyKey?: string | symbol + propertyKey?: string | symbol, ): void { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); @@ -1019,7 +1019,7 @@ namespace Reflect { metadataKey, metadataValue, target, - propertyKey + propertyKey, ); } @@ -1032,7 +1032,7 @@ namespace Reflect { function hasMetadata( metadataKey: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): boolean; /** @@ -1072,7 +1072,7 @@ namespace Reflect { function hasMetadata( metadataKey: any, target: any, - propertyKey?: string | symbol + propertyKey?: string | symbol, ): boolean { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); @@ -1088,7 +1088,7 @@ namespace Reflect { function hasOwnMetadata( metadataKey: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): boolean; /** @@ -1128,7 +1128,7 @@ namespace Reflect { function hasOwnMetadata( metadataKey: any, target: any, - propertyKey?: string | symbol + propertyKey?: string | symbol, ): boolean { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); @@ -1144,7 +1144,7 @@ namespace Reflect { function getMetadata( metadataKey: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): any; /** @@ -1184,7 +1184,7 @@ namespace Reflect { function getMetadata( metadataKey: any, target: any, - propertyKey?: string | symbol + propertyKey?: string | symbol, ): any { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); @@ -1200,7 +1200,7 @@ namespace Reflect { function getOwnMetadata( metadataKey: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): any; /** @@ -1240,7 +1240,7 @@ namespace Reflect { function getOwnMetadata( metadataKey: any, target: any, - propertyKey?: string | symbol + propertyKey?: string | symbol, ): any { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); @@ -1290,7 +1290,7 @@ namespace Reflect { */ function getMetadataKeys( target: any, - propertyKey?: string | symbol + propertyKey?: string | symbol, ): any[] { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); @@ -1305,7 +1305,7 @@ namespace Reflect { function getOwnMetadataKeys(target: any): any[]; function getOwnMetadataKeys( target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): any[]; /** @@ -1343,7 +1343,7 @@ namespace Reflect { */ function getOwnMetadataKeys( target: any, - propertyKey?: string | symbol + propertyKey?: string | symbol, ): any[] { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); @@ -1359,7 +1359,7 @@ namespace Reflect { function deleteMetadata( metadataKey: any, target: any, - propertyKey: string | symbol + propertyKey: string | symbol, ): boolean; /** @@ -1399,14 +1399,14 @@ namespace Reflect { function deleteMetadata( metadataKey: any, target: any, - propertyKey?: string | symbol + propertyKey?: string | symbol, ): boolean { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); const metadataMap = GetOrCreateMetadataMap( target, propertyKey, - /*Create*/ false + /*Create*/ false, ); if (IsUndefined(metadataMap)) return false; if (!metadataMap.delete(metadataKey)) return false; @@ -1422,14 +1422,14 @@ namespace Reflect { function DecorateConstructor( decorators: ClassDecorator[], - target: Function + target: Function, ): Function { for (let i = decorators.length - 1; i >= 0; --i) { const decorator = decorators[i]; const decorated = decorator(target); if (!IsUndefined(decorated) && !IsNull(decorated)) { if (!IsConstructor(decorated)) throw new TypeError(); - target = decorated; + target = decorated; } } return target; @@ -1439,14 +1439,14 @@ namespace Reflect { decorators: MemberDecorator[], target: any, propertyKey: string | symbol, - descriptor: PropertyDescriptor | undefined + descriptor: PropertyDescriptor | undefined, ): PropertyDescriptor | undefined { for (let i = decorators.length - 1; i >= 0; --i) { const decorator = decorators[i]; const decorated = decorator(target, propertyKey, descriptor); if (!IsUndefined(decorated) && !IsNull(decorated)) { if (!IsObject(decorated)) throw new TypeError(); - descriptor = decorated; + descriptor = decorated; } } return descriptor; @@ -1457,17 +1457,17 @@ namespace Reflect { function GetOrCreateMetadataMap( O: any, P: string | symbol | undefined, - Create: true + Create: true, ): Map; function GetOrCreateMetadataMap( O: any, P: string | symbol | undefined, - Create: false + Create: false, ): Map | undefined; function GetOrCreateMetadataMap( O: any, P: string | symbol | undefined, - Create: boolean + Create: boolean, ): Map | undefined { let targetMetadata = Metadata.get(O); if (IsUndefined(targetMetadata)) { @@ -1489,7 +1489,7 @@ namespace Reflect { function OrdinaryHasMetadata( MetadataKey: any, O: any, - P: string | symbol | undefined + P: string | symbol | undefined, ): boolean { const hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); if (hasOwn) return true; @@ -1503,7 +1503,7 @@ namespace Reflect { function OrdinaryHasOwnMetadata( MetadataKey: any, O: any, - P: string | symbol | undefined + P: string | symbol | undefined, ): boolean { const metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return false; @@ -1515,7 +1515,7 @@ namespace Reflect { function OrdinaryGetMetadata( MetadataKey: any, O: any, - P: string | symbol | undefined + P: string | symbol | undefined, ): any { const hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); if (hasOwn) return OrdinaryGetOwnMetadata(MetadataKey, O, P); @@ -1529,7 +1529,7 @@ namespace Reflect { function OrdinaryGetOwnMetadata( MetadataKey: any, O: any, - P: string | symbol | undefined + P: string | symbol | undefined, ): any { const metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return undefined; @@ -1542,7 +1542,7 @@ namespace Reflect { MetadataKey: any, MetadataValue: any, O: any, - P: string | symbol | undefined + P: string | symbol | undefined, ): void { const metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ true); metadataMap.set(MetadataKey, MetadataValue); @@ -1552,7 +1552,7 @@ namespace Reflect { // https://rbuckton.github.io/reflect-metadata/#ordinarymetadatakeys function OrdinaryMetadataKeys( O: any, - P: string | symbol | undefined + P: string | symbol | undefined, ): any[] { const ownKeys = OrdinaryOwnMetadataKeys(O, P); const parent = OrdinaryGetPrototypeOf(O); @@ -1583,7 +1583,7 @@ namespace Reflect { // https://rbuckton.github.io/reflect-metadata/#ordinaryownmetadatakeys function OrdinaryOwnMetadataKeys( O: any, - P: string | symbol | undefined + P: string | symbol | undefined, ): any[] { const keys: any[] = []; const metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); @@ -1642,7 +1642,7 @@ namespace Reflect { String, Symbol, Number, - Object + Object, } // 6.1.1 The Undefined Type @@ -1666,7 +1666,7 @@ namespace Reflect { // 6.1.7 The Object Type // https://tc39.github.io/ecma262/#sec-object-type function IsObject< - T + T, >(x: T | undefined | null | boolean | string | symbol | number): x is T { return typeof x === "object" ? x !== null : typeof x === "function"; } @@ -1678,7 +1678,7 @@ namespace Reflect { // https://tc39.github.io/ecma262/#sec-toprimitive function ToPrimitive( input: any, - PreferredType?: Tag + PreferredType?: Tag, ): undefined | null | boolean | string | symbol | number { switch (Type(input)) { case Tag.Undefined: @@ -1694,12 +1694,11 @@ namespace Reflect { case Tag.Number: return input; } - const hint: "string" | "number" | "default" = - PreferredType === Tag.String - ? "string" - : PreferredType === Tag.Number - ? "number" - : "default"; + const hint: "string" | "number" | "default" = PreferredType === Tag.String + ? "string" + : PreferredType === Tag.Number + ? "number" + : "default"; const exoticToPrim = GetMethod(input, toPrimitiveSymbol); if (exoticToPrim !== undefined) { const result = exoticToPrim.call(input, hint); @@ -1713,7 +1712,7 @@ namespace Reflect { // https://tc39.github.io/ecma262/#sec-ordinarytoprimitive function OrdinaryToPrimitive( O: any, - hint: "string" | "number" + hint: "string" | "number", ): undefined | null | boolean | string | symbol | number { if (hint === "string") { const toString = O.toString; @@ -1866,8 +1865,9 @@ namespace Reflect { // If the super prototype is Object.prototype, null, or undefined, then we cannot determine the heritage. const prototype = O.prototype; const prototypeProto = prototype && Object.getPrototypeOf(prototype); - if (prototypeProto == null || prototypeProto === Object.prototype) + if (prototypeProto == null || prototypeProto === Object.prototype) { return proto; + } // If the constructor was not a function, then we cannot determine the heritage. const constructor = prototypeProto.constructor; @@ -1888,7 +1888,7 @@ namespace Reflect { class MapIterator< K, V, - R extends K | V | [K, V] + R extends K | V | [K, V], > implements IterableIterator { private _keys: K[]; private _values: V[]; @@ -1910,7 +1910,7 @@ namespace Reflect { if (index >= 0 && index < this._keys.length) { const result = this._selector( this._keys[index], - this._values[index] + this._values[index], ); if (index + 1 >= this._keys.length) { this._index = -1; @@ -1921,7 +1921,7 @@ namespace Reflect { } return { value: result, done: false }; } - return { value: undefined, done: true }; + return { value: undefined, done: true }; } throw(error: any): IteratorResult { if (this._index >= 0) { @@ -1937,7 +1937,7 @@ namespace Reflect { this._keys = arraySentinel; this._values = arraySentinel; } - return { value: value, done: true }; + return { value: value, done: true }; } } @@ -2097,28 +2097,27 @@ namespace Reflect { function CreateUniqueKey(): string { let key: string; - do key = "@@WeakMap@@" + CreateUUID(); - while (HashMap.has(keys, key)); + do key = "@@WeakMap@@" + CreateUUID(); while (HashMap.has(keys, key)); keys[key] = true; return key; } function GetOrCreateWeakMapTable< - K + K, >(target: K, create: true): HashMap; function GetOrCreateWeakMapTable< - K + K, >(target: K, create: false): HashMap | undefined; function GetOrCreateWeakMapTable< - K + K, >(target: K, create: boolean): HashMap | undefined { if (!hasOwn.call(target, rootKey)) { if (!create) return undefined; Object.defineProperty(target, rootKey, { - value: HashMap.create() + value: HashMap.create(), }); } - return (target)[rootKey]; + return ( target)[rootKey]; } function FillRandomBytes(buffer: BufferLike, size: number): BufferLike { @@ -2128,10 +2127,12 @@ namespace Reflect { function GenRandomBytes(size: number): BufferLike { if (typeof Uint8Array === "function") { - if (typeof crypto !== "undefined") + if (typeof crypto !== "undefined") { return crypto.getRandomValues(new Uint8Array(size)) as Uint8Array; - if (typeof msCrypto !== "undefined") + } + if (typeof msCrypto !== "undefined") { return msCrypto.getRandomValues(new Uint8Array(size)) as Uint8Array; + } return FillRandomBytes(new Uint8Array(size), size); } return FillRandomBytes(new Array(size), size); @@ -2155,8 +2156,8 @@ namespace Reflect { // uses a heuristic used by v8 and chakra to force an object into dictionary mode. function MakeDictionary(obj: T): T { - (obj).__ = undefined; - delete (obj).__; + ( obj).__ = undefined; + delete ( obj).__; return obj; } }); diff --git a/src/dso.ts b/src/dso.ts index f300633..f2bbca1 100644 --- a/src/dso.ts +++ b/src/dso.ts @@ -66,5 +66,9 @@ export const dso = { await _client.connect(config); } return _client; - } + }, + + close(): void { + _client.close(); + }, }; diff --git a/src/field.ts b/src/field.ts index 40612ed..fb50f4b 100644 --- a/src/field.ts +++ b/src/field.ts @@ -3,7 +3,7 @@ import { camel2line } from "./util.ts"; export enum Defaults { CURRENT_TIMESTAMP = "CURRENT_TIMESTAMP", - NULL = "NULL" + NULL = "NULL", } /** Field type */ @@ -14,7 +14,7 @@ export enum FieldType { TEXT, BOOLEAN, LONGTEXT, - GeoPOINT + GeoPOINT, } /** Field Decorator */ diff --git a/src/model.ts b/src/model.ts index c66ec16..1592251 100644 --- a/src/model.ts +++ b/src/model.ts @@ -39,7 +39,7 @@ export class BaseModel { /** get primary key */ get primaryKey(): FieldOptions | undefined { - return this.modelFields.find(field => field.primary); + return this.modelFields.find((field) => field.primary); } /** get defined fields list */ @@ -51,14 +51,14 @@ export class BaseModel { default: Defaults.CURRENT_TIMESTAMP, autoUpdate: true, name: "updated_at", - property: "updated_at" + property: "updated_at", }, { type: FieldType.DATE, default: Defaults.CURRENT_TIMESTAMP, name: "created_at", - property: "created_at" - } + property: "created_at", + }, ] ); } @@ -79,8 +79,10 @@ export class BaseModel { if (!data) return; const model: any = {}; const fieldsMapping: any = {}; - this.modelFields.map(field => (fieldsMapping[field.name] = field.property)); - Object.keys(data).forEach(key => { + this.modelFields.map( + (field) => (fieldsMapping[field.name] = field.property) + ); + Object.keys(data).forEach((key) => { const propertyName = fieldsMapping[key]; model[propertyName || key] = data[key]; }); @@ -95,9 +97,9 @@ export class BaseModel { const data: any = {}; const fieldsMapping: any = {}; this.modelFields.map( - field => (fieldsMapping[field.property!] = field.name) + (field) => (fieldsMapping[field.property!] = field.name), ); - Object.keys(model).forEach(key => { + Object.keys(model).forEach((key) => { const name = fieldsMapping[key]; data[name || key] = model[key as keyof ModelFields]; }); @@ -116,10 +118,10 @@ export class BaseModel { if (options.group) query.groupBy(...options.group); if (options.having) query.having(options.having); if (options.join) { - options.join.forEach(join => query.join(join)); + options.join.forEach((join) => query.join(join)); } if (options.limit) query.limit(...options.limit); - if (options.order) options.order.forEach(order => query.order(order)); + if (options.order) options.order.forEach((order) => query.order(order)); return query; } @@ -128,11 +130,11 @@ export class BaseModel { * @param where conditions */ async findOne( - options: Where | QueryOptions + options: Where | QueryOptions, ): Promise | undefined> { if (options instanceof Where) { options = { - where: options + where: options, }; } const result = await this.query(this.optionsToQuery(options).limit(0, 1)); @@ -147,7 +149,7 @@ export class BaseModel { const result = await this.execute( this.builder() .delete() - .where(where) + .where(where), ); return result.affectedRows ?? 0; } @@ -156,11 +158,11 @@ export class BaseModel { async findAll(options: Where | QueryOptions): Promise[]> { if (options instanceof Where) { options = { - where: options + where: options, }; } const result = await this.query(this.optionsToQuery(options)); - return result.map(record => this.convertModel(record)!); + return result.map((record) => this.convertModel(record)!); } /** find one record by primary key */ @@ -179,7 +181,7 @@ export class BaseModel { /** update records by given conditions */ async update( data: Partial, - where?: Where + where?: Where, ): Promise { if ( !where && @@ -187,7 +189,7 @@ export class BaseModel { data[this.primaryKey.property as keyof this] ) { where = Where.field(this.primaryKey.name).eq( - data[this.primaryKey.property as keyof this] + data[this.primaryKey.property as keyof this], ); } const query = this.builder() diff --git a/src/sync.ts b/src/sync.ts index 2dd5e80..c650ff2 100644 --- a/src/sync.ts +++ b/src/sync.ts @@ -9,7 +9,7 @@ export async function sync(client: Client, model: BaseModel, force: boolean) { } let defs = model.modelFields - .map(field => { + .map((field) => { let def = field.name; let type = ""; switch (field.type) { @@ -50,7 +50,7 @@ export async function sync(client: Client, model: BaseModel, force: boolean) { if (field.autoUpdate) { assert( field.type === FieldType.DATE, - "AutoUpdate only support Date field" + "AutoUpdate only support Date field", ); def += ` ON UPDATE CURRENT_TIMESTAMP()`; } @@ -68,7 +68,7 @@ export async function sync(client: Client, model: BaseModel, force: boolean) { "(", defs, ")", - "ENGINE=InnoDB DEFAULT CHARSET=utf8;" + "ENGINE=InnoDB DEFAULT CHARSET=utf8;", ].join(" "); dso.showQueryLog && console.log(`\n[ DSO:SYNC ]\nSQL:\t ${sql}\n`); diff --git a/src/transaction.ts b/src/transaction.ts index 9ae0c9e..d7819d1 100644 --- a/src/transaction.ts +++ b/src/transaction.ts @@ -10,9 +10,9 @@ export class Transaction { } static async transaction( - processor: (transaction: Transaction) => Promise + processor: (transaction: Transaction) => Promise, ): Promise { - return (await dso.client.transaction(async conn => { + return (await dso.client.transaction(async (conn) => { const trans = new Transaction(conn); return await processor(trans); })) as T; diff --git a/src/util.ts b/src/util.ts index c2bc95a..aa68843 100644 --- a/src/util.ts +++ b/src/util.ts @@ -5,7 +5,7 @@ export function camel2line(key: string) { // 下划线转驼峰 export function line2camel(key: string) { - return key.replace(/_(\w)/g, function(_, letter) { + return key.replace(/_(\w)/g, function (_, letter) { return letter.toUpperCase(); }); } diff --git a/test.ts b/test.ts index bca0f66..f26ffed 100644 --- a/test.ts +++ b/test.ts @@ -2,6 +2,16 @@ import { Client } from "./deps.ts"; import { dso } from "./mod.ts"; import "./test/model.ts"; +const config = { + hostname: "127.0.0.1", + port: 3306, + poolSize: 3, + debug: false, + username: "root", + password: "", + db: "", +}; + const client = new Client(); dso.showQueryLog = false; @@ -9,28 +19,19 @@ export async function clientTest(fn: Function) { Deno.test({ name: fn.name, fn: async () => { + await dso.connect({ ...config, db: "test_orm" }); await dso.sync(true); await fn(); - } + dso.close(); + }, }); } async function main() { - const config = { - hostname: "127.0.0.1", - port: 3306, - poolSize: 3, - debug: false, - username: "root", - password: "", - db: "" - }; await client.connect(config); await client.execute(`CREATE DATABASE IF NOT EXISTS test_orm`); await client.execute(`USE test_orm`); await client.close(); - await dso.connect({ ...config, db: "test_orm" }); - await Deno.runTests(); } -main(); +await main(); diff --git a/test/model.ts b/test/model.ts index b905f9b..7c66bd7 100644 --- a/test/model.ts +++ b/test/model.ts @@ -7,7 +7,7 @@ import { Join, Model, Query, - Where + Where, } from "../mod.ts"; import { clientTest } from "../test.ts"; @@ -17,7 +17,7 @@ class UserModel extends BaseModel { type: FieldType.INT, primary: true, length: 11, - autoIncrement: true + autoIncrement: true, }) id!: number; @@ -50,16 +50,16 @@ clientTest(async function testInsert() { assertEquals( await userModel.insert({ nickName: "foo", - password: "bar" + password: "bar", }), - 1 + 1, ); assertEquals( await userModel.insert({ nickName: "foo", - password: "bar" + password: "bar", }), - 2 + 2, ); }); @@ -68,9 +68,9 @@ clientTest(async function testUpdate() { assertEquals( await userModel.update({ id, - password: "BAR" + password: "BAR", }), - 1 + 1, ); const user = await userModel.findById(id!); assertEquals(user, { @@ -79,7 +79,7 @@ clientTest(async function testUpdate() { defaultVal: 0, id: 1, nickName: "foo", - password: "BAR" + password: "BAR", }); }); @@ -90,8 +90,8 @@ clientTest(async function testFindOneByWhere() { Where.and( Where.field("id").eq(1), Where.field("password").isNull(), - Where.field("default_val").lt(10) - ) + Where.field("default_val").lt(10), + ), ); const topic = await topicModel.findById(1); assertEquals(user, { @@ -100,7 +100,7 @@ clientTest(async function testFindOneByWhere() { password: null, defaultVal: 0, updated_at: user?.updated_at, - created_at: user?.created_at + created_at: user?.created_at, }); assert(!!topic?.created_at); assertEquals(topic, { @@ -108,7 +108,7 @@ clientTest(async function testFindOneByWhere() { created_at: topic?.created_at, id: 1, title: "foo", - userId: 1 + userId: 1, }); }); @@ -117,7 +117,7 @@ clientTest(async function testDelete() { await userModel.insert({ nickName: "bar" }); await userModel.insert({ nickName: "noo" }); const count = await userModel.delete( - Where.or(Where.field("id").eq(1), Where.field("nick_name").eq("noo")) + Where.or(Where.field("id").eq(1), Where.field("nick_name").eq("noo")), ); assertEquals(count, 2); @@ -130,13 +130,13 @@ clientTest(async function testFindOneByOptions() { where: Where.and( Where.field("id").eq(1), Where.field("password").isNull(), - Where.field("default_val").lt(10) - ) + Where.field("default_val").lt(10), + ), }); const topic = await topicModel.findOne({ where: Where.field("topics.id").eq(1), fields: ["topics.*", "users.nick_name as userNickName"], - join: [Join.left("users").on("users.id", "topics.user_id")] + join: [Join.left("users").on("users.id", "topics.user_id")], }); assert(!!topic?.created_at); assert(!!topic?.updated_at); @@ -146,7 +146,7 @@ clientTest(async function testFindOneByOptions() { userId: 1, userNickName: "foo", updated_at: topic?.updated_at, - created_at: topic?.created_at + created_at: topic?.created_at, }); }); @@ -154,7 +154,7 @@ clientTest(async function testTransactionFail() { let userId: number | undefined; let topicId: number | undefined; await assertThrowsAsync(async () => { - await dso.transaction(async trans => { + await dso.transaction(async (trans) => { const userModel = trans.getModel(UserModel); const topicModel = trans.getModel(TopicModel); userId = await userModel.insert({ nickName: "foo", password: "bar" }); @@ -174,7 +174,7 @@ clientTest(async function testTransactionFail() { clientTest(async function testTransactionSuccess() { let topicId: number | undefined; let userId: number | undefined; - const result = await dso.transaction(async trans => { + const result = await dso.transaction(async (trans) => { const userModel = trans.getModel(UserModel); const topicModel = trans.getModel(TopicModel); userId = await userModel.insert({ nickName: "foo", password: "bar" }); diff --git a/util.ts b/util.ts index eb75a45..aa68843 100644 --- a/util.ts +++ b/util.ts @@ -1,11 +1,11 @@ // 驼峰转下划线 export function camel2line(key: string) { - return key.replace(/([A-Z])/g, "_$1").toLowerCase(); + return key.replace(/([A-Z])/g, "_$1").toLowerCase(); } // 下划线转驼峰 export function line2camel(key: string) { - return key.replace(/_(\w)/g, function (_, letter) { - return letter.toUpperCase(); - }); -} \ No newline at end of file + return key.replace(/_(\w)/g, function (_, letter) { + return letter.toUpperCase(); + }); +}