ddStore
sequelize查询方式
投影查询
textmodel.findAll({ attributes:["username","password"] })
or查询
textmodel.findOne(){ where:{ [Op.or]:[{username:"zs"},{password:"123"}] } }
模糊查询
textmodel.findAll({ where:{ username:{ [Op.like]:"王%" } } })
聚合查询
textmodel.findAll({ group:"address", attribute:["address",[Sequelize.fn("count",Sequelize.col("valid")),"total"]], where:{ valid:1 } })
1. 表关联设置
目标的删除和更新策略
- CASCADE 级联策略。适用此种策略时主表的记录被删除或者主键字段被修改时汇通不删除或修改子表。
- NO ACTION 无动作策略。适用此种策略时要删除主表必须删除子表,要删除主表的记录必须先删除子表的关联的记录,不能更新主表主键字段的值。
- RESTRICT 主表约束策略。此种策略对主表的约束和NO ACTION一样。
- SET NO 置空策略。使用此种策略时,如果主表被删除或者逐渐被修改,则将子表的外键设置为NULL。需要注意的是,如果子表的外键是主键或者是设置为NOT NULL的,则主表的删除和主键的更改跟NO ACTION一样。
2.装饰器重构Koa路由
为什么要使用装饰器重构路由
类和装饰器可集中管理路由,大幅提升代码可读性
-
类装饰器
textfunction prefix(prefix: string) { return function (target: new (...args: any[]) => any) { const router = new Router({ prefix }); // 遍历类中所有的方法 => defineMeta时保存的key for (let fn in target.prototype) { // 获取路径和方法 const path = Reflect.getMetadata("path", target.prototype, fn); const type: IRequestType = Reflect.getMetadata( "type", target.prototype, fn ); const middlewareArr: Middleware[] = Reflect.getMetadata( "middleware", target.prototype, fn ); if (middlewareArr) { router[type](path, ...middlewareArr, target.prototype[fn]); } else { router[type](path, target.prototype[fn]); } // router上添加路由 } // 载入rootRouter rootRouter.use(router.routes(), router.allowedMethods()); }; } -
方法装饰器
textfunction getMethodDecorator(type: IRequestType) { return function (path: string) { return function (target: any, key: string, desc: PropertyDescriptor) { // 元信息保存路径名 Reflect.defineMetadata("path", path, target, key); // 元信息保存方法名 Reflect.defineMetadata("type", type, target, key); }; }; } const get = getMethodDecorator(IRequestType.GET); -
中间件装饰器
textfunction use(middleware: Middleware) { return function (target: any, key: string) { // 先获取中间件 let mw: Middleware[] = Reflect.getMetadata("middleware", target, key); if (!mw) { // 没有中间件 mw = [middleware]; } else { mw.push(middleware); } // 定义中间件 Reflect.defineMetadata("middleware", mw, target, key); }; }