常年使用sails 开发node 后端 苦不堪言,文档缺失,迭代较慢,并且周边也不是那么完善,虽说基本能满足需求 但是还是少了灵活性。 待到egg 推出之时就在观察,最近新开项目遂采用egg - ts
egg-mysql
这玩意没有index.d.ts .所以 你想使用app.mysql 是编译不过的,所以要用 ts 的merge 来给Application上挂载一个mysql 我们可以这么做
./typings/index.d.ts 写入
declare module 'egg' {
interface mysql {
get(tableName: String, find: {}): Promise
query(sql: String, values: Any[]): Promise
}
interface Application {
mysql: mysql;
}
}
可以在上面给mysql 加点方法这样就有提示了。
egg-sequelize
为node中较为常用的orm 框架。
这个玩意我们可以细说。
首先你要做一个model 来定义这个表中的字段,但是为了方便开发,我们得加点料。
/app/model/model.ts 这里写一个基类的basemodel 这样以后所有的model都可以用到基类
import { Application } from 'egg';
import { snakeCase } from 'lodash';
import * as moment from 'moment';
import { DefineAttributes, SequelizeStatic } from 'sequelize';
export default function BaseModel(
app: Application,
table: string,
attributes: DefineAttributes,
options: object = {},
) {
const { Op, UUID, UUIDV4 } = app.Sequelize;
const modelSchema = app.model.define(table, {
id: {
type: UUID,
unique: true,
primaryKey: true,
allowNull: false,
defaultValue: UUIDV4,
},
...attributes,
...getDefaultAttributes(opt