Skip to content

Commit

Permalink
use strict mode
Browse files Browse the repository at this point in the history
  • Loading branch information
manyuanrong committed Mar 6, 2020
1 parent 2eedfc9 commit 5c1fce2
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 83 deletions.
21 changes: 17 additions & 4 deletions deps.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
export { assert, assertEquals, assertThrowsAsync } from "https://deno.land/[email protected]/testing/asserts.ts";
export { runTests, test, TestFunction } from "https://deno.land/[email protected]/testing/mod.ts";
export { Client, ClientConfig, Connection } from "https://deno.land/x/[email protected]/mod.ts";
export { Join, Order, Query, replaceParams, Where } from "https://deno.land/x/[email protected]/mod.ts";
export {
assert,
assertEquals,
assertThrowsAsync
} from "https://deno.land/[email protected]/testing/asserts.ts";
export {
Client,
ClientConfig,
Connection
} from "https://deno.land/x/[email protected]/mod.ts";
export {
Join,
Order,
Query,
replaceParams,
Where
} from "https://deno.land/x/[email protected]/mod.ts";

import "./src/Reflect.ts";
16 changes: 0 additions & 16 deletions package.json

This file was deleted.

1 change: 1 addition & 0 deletions src/Reflect.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// @ts-nocheck
/*! *****************************************************************************
Copyright (C) Microsoft. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
Expand Down
4 changes: 2 additions & 2 deletions src/dso.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { sync } from "./sync.ts";
import { Transaction } from "./transaction.ts";

/** @ignore */
let _client: Client = null;
let _client: Client;

/** @ignore */
let _models: BaseModel[] = [];
Expand All @@ -22,7 +22,7 @@ export const dso = {
* Sync model to database table
* @param force set true, will drop table before create table
*/
async sync(force: boolean = false) {
async sync(force: boolean = false): Promise<void> {
for (const model of _models) {
await sync(_client, model, force);
}
Expand Down
12 changes: 6 additions & 6 deletions src/field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { BaseModel } from "./model.ts";
import { camel2line } from "./util.ts";

export enum Defaults {
CURRENT_TIMESTAMP = "CURRENT_TIMESTAMP",
CURRENT_TIMESTAMP = "CURRENT_TIMESTAMP",
NULL = "NULL"
}

Expand All @@ -12,13 +12,13 @@ export enum FieldType {
INT,
STRING,
TEXT,
BOOLEAN,
LONGTEXT,
GeoPOINT,
BOOLEAN,
LONGTEXT,
GeoPOINT
}

/** Field Decorator */
export function Field(options: FieldOptions) {
export function Field(options: Partial<FieldOptions> & { type: FieldType }) {
return (target: BaseModel, property: string) => {
const fields = target.modelFields;
const name = camel2line(property);
Expand All @@ -29,7 +29,7 @@ export function Field(options: FieldOptions) {

/** Field Options */
export interface FieldOptions {
name?: string;
name: string;
type: FieldType;
property?: string;
primary?: boolean;
Expand Down
55 changes: 34 additions & 21 deletions src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ export type ModelFields<T> = Partial<Omit<T, keyof BaseModel>> & {

/** Model base class */
export class BaseModel {
created_at: Date;
updated_at: Date;
created_at?: Date;
updated_at?: Date;

constructor(public connection?: Connection) {}

Expand All @@ -38,7 +38,7 @@ export class BaseModel {
}

/** get primary key */
get primaryKey(): FieldOptions {
get primaryKey(): FieldOptions | undefined {
return this.modelFields.find(field => field.primary);
}

Expand Down Expand Up @@ -73,10 +73,12 @@ export class BaseModel {
* Convert data object to model
* @param data
*/
private convertModel(data: Object): ModelFields<this> {
if (!data) return null;
const model = {};
const fieldsMapping = {};
private convertModel(data: {
[key: string]: any;
}): ModelFields<this> | undefined {
if (!data) return;
const model: any = {};
const fieldsMapping: any = {};
this.modelFields.map(field => (fieldsMapping[field.name] = field.property));
Object.keys(data).forEach(key => {
const propertyName = fieldsMapping[key];
Expand All @@ -89,13 +91,15 @@ export class BaseModel {
* Convert model object to db object
* @param model
*/
private convertObject(model: ModelFields<this>): Object {
const data = {};
const fieldsMapping = {};
this.modelFields.map(field => (fieldsMapping[field.property] = field.name));
private convertObject(model: ModelFields<this>): { [key: string]: any } {
const data: any = {};
const fieldsMapping: any = {};
this.modelFields.map(
field => (fieldsMapping[field.property!] = field.name)
);
Object.keys(model).forEach(key => {
const name = fieldsMapping[key];
data[name || key] = model[key];
data[name || key] = model[key as keyof ModelFields<this>];
});
return data;
}
Expand Down Expand Up @@ -123,7 +127,9 @@ export class BaseModel {
* find one record
* @param where conditions
*/
async findOne(options: Where | QueryOptions): Promise<ModelFields<this>> {
async findOne(
options: Where | QueryOptions
): Promise<ModelFields<this> | undefined> {
if (options instanceof Where) {
options = {
where: options
Expand All @@ -143,7 +149,7 @@ export class BaseModel {
.delete()
.where(where)
);
return result.affectedRows;
return result.affectedRows ?? 0;
}

/** find all records by given conditions */
Expand All @@ -154,32 +160,39 @@ export class BaseModel {
};
}
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 */
async findById(id: string | number): Promise<ModelFields<this>> {
async findById(id: string | number): Promise<ModelFields<this> | undefined> {
assert(!!this.primaryKey);
return await this.findOne(Where.field(this.primaryKey.name).eq(id));
}

/** insert record */
async insert(fields: Partial<this>): Promise<number> {
async insert(fields: Partial<this>): Promise<number | undefined> {
const query = this.builder().insert(this.convertObject(fields));
const result = await this.execute(query);
return result.lastInsertId;
}

/** update records by given conditions */
async update(data: Partial<this>, where?: Where): Promise<number> {
if (!where && this.primaryKey && data[this.primaryKey.property]) {
async update(
data: Partial<this>,
where?: Where
): Promise<number | undefined> {
if (
!where &&
this.primaryKey &&
data[this.primaryKey.property as keyof this]
) {
where = Where.field(this.primaryKey.name).eq(
data[this.primaryKey.property]
data[this.primaryKey.property as keyof this]
);
}
const query = this.builder()
.update(this.convertObject(data))
.where(where);
.where(where ?? "");

const result = await this.execute(query);
return result.affectedRows;
Expand Down
8 changes: 4 additions & 4 deletions test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Client, runTests, test, TestFunction } from "./deps.ts";
import { Client } from "./deps.ts";
import { dso } from "./mod.ts";
import "./test/model.ts";

const client = new Client();
dso.showQueryLog = false;

export async function clientTest(fn: TestFunction) {
test({
export async function clientTest(fn: Function) {
Deno.test({
name: fn.name,
fn: async () => {
await dso.sync(true);
Expand All @@ -30,7 +30,7 @@ async function main() {
await client.execute(`USE test_orm`);
await client.close();
await dso.connect({ ...config, db: "test_orm" });
await runTests();
await Deno.runTests();
}

main();
60 changes: 30 additions & 30 deletions test/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,28 +19,28 @@ class UserModel extends BaseModel {
length: 11,
autoIncrement: true
})
id: number;
id!: number;

@Field({ type: FieldType.STRING, length: 30 })
nickName: string;
nickName?: string;

@Field({ type: FieldType.STRING, length: 30 })
password: string;
password?: string;

@Field({ type: FieldType.INT, default: 0 })
defaultVal: string;
defaultVal?: string;
}

@Model("topics")
class TopicModel extends BaseModel {
@Field({ type: FieldType.INT, autoIncrement: true, primary: true })
id: number;
id!: number;

@Field({ type: FieldType.INT, notNull: true })
userId: number;
userId?: number;

@Field({ type: FieldType.STRING })
title: string;
title?: string;
}

const userModel = dso.define(UserModel);
Expand All @@ -64,18 +64,18 @@ clientTest(async function testInsert() {
});

clientTest(async function testUpdate() {
const id: number = await userModel.insert({ nickName: "foo" });
const id: number | undefined = await userModel.insert({ nickName: "foo" });
assertEquals(
await userModel.update({
id,
password: "BAR"
}),
1
);
const user = await userModel.findById(id);
const user = await userModel.findById(id!);
assertEquals(user, {
updated_at: user.updated_at,
created_at: user.created_at,
updated_at: user?.updated_at,
created_at: user?.created_at,
defaultVal: 0,
id: 1,
nickName: "foo",
Expand All @@ -99,13 +99,13 @@ clientTest(async function testFindOneByWhere() {
nickName: "foo",
password: null,
defaultVal: 0,
updated_at: user.updated_at,
created_at: user.created_at
updated_at: user?.updated_at,
created_at: user?.created_at
});
assert(!!topic.created_at);
assert(!!topic?.created_at);
assertEquals(topic, {
updated_at: topic.updated_at,
created_at: topic.created_at,
updated_at: topic?.updated_at,
created_at: topic?.created_at,
id: 1,
title: "foo",
userId: 1
Expand Down Expand Up @@ -138,53 +138,53 @@ clientTest(async function testFindOneByOptions() {
fields: ["topics.*", "users.nick_name as userNickName"],
join: [Join.left("users").on("users.id", "topics.user_id")]
});
assert(!!topic.created_at);
assert(!!topic.updated_at);
assert(!!topic?.created_at);
assert(!!topic?.updated_at);
assertEquals(topic, {
id: 1,
title: "foo",
userId: 1,
userNickName: "foo",
updated_at: topic.updated_at,
created_at: topic.created_at
updated_at: topic?.updated_at,
created_at: topic?.created_at
});
});

clientTest(async function testTransactionFail() {
let userId: number;
let topicId: number;
let userId: number | undefined;
let topicId: number | undefined;
await assertThrowsAsync(async () => {
await dso.transaction<boolean>(async trans => {
const userModel = trans.getModel(UserModel);
const topicModel = trans.getModel(TopicModel);
userId = await userModel.insert({ nickName: "foo", password: "bar" });
topicId = await topicModel.insert({ title: "zoo", userId });
let user = await userModel.findById(userId);
let user = await userModel.findById(userId!);
assert(!!user);
await userModel.query(new Query().table("notexixts").select("*"));
return true;
});
});
const user = await userModel.findById(userId);
const topic = await topicModel.findById(topicId);
const user = await userModel.findById(userId!);
const topic = await topicModel.findById(topicId!);
assert(!user);
assert(!topic);
});

clientTest(async function testTransactionSuccess() {
let topicId: number;
let userId: number;
let topicId: number | undefined;
let userId: number | undefined;
const result = await dso.transaction<boolean>(async trans => {
const userModel = trans.getModel(UserModel);
const topicModel = trans.getModel(TopicModel);
userId = await userModel.insert({ nickName: "foo", password: "bar" });
topicId = await topicModel.insert({ title: "zoo", userId });
let user = await userModel.findById(userId);
let user = await userModel.findById(userId!);
assert(!!user);
return true;
});
const user = await userModel.findById(userId);
const topic = await userModel.findById(topicId);
const user = await userModel.findById(userId!);
const topic = await userModel.findById(topicId!);
assertEquals(result, true);
assert(!!topic);
assert(!!user);
Expand Down

0 comments on commit 5c1fce2

Please sign in to comment.