CabloyJS对EggJS中的数据库操作方法进行了进一步封装和扩展,提供了以下机制:

  1. 提供ctx.db对象,可以便利的支持数据库事务
  2. 提供model对象,可以便利的支持多实例软删除

ctx.db对象

EggJS是在app对象上提供数据库连接对象,而CabloyJS在ctx对象上提供数据库连接对象,便于在启动数据库事务时,在上下文环境中保持同一个数据库连接。在这里,我们先看看通过ctx.db如何完成常规的增删改查等操作

ctx.db提供的数据库操作方法与EggJS基本一致

在模块test-party中,有一个数据表testParty,我们新增后端API路由kitchen-sink/guide/echo6,在其对应的控制器方法中进行testParty增删改查等操作

src/suite-vendor/test-party/modules/test-party/backend/src/controller/kitchen-sink/guide.js

  1. 1async echo6() {
  2. 2 // testParty: insert/udpate/delete/get
  3. 3
  4. 4 // insert
  5. 5 const res = await this.ctx.db.insert('testParty', {
  6. 6 iid: this.ctx.instance.id,
  7. 7 deleted: 0,
  8. 8 personCount: 3,
  9. 9 });
  10. 10 const id = res.insertId;
  11. 11 // update
  12. 12 await this.ctx.db.update('testParty', {
  13. 13 id,
  14. 14 personCount: 5,
  15. 15 });
  16. 16 // get
  17. 17 const item = await this.ctx.db.get('testParty', {
  18. 18 id,
  19. 19 });
  20. 20 // delete
  21. 21 await this.ctx.db.delete('testParty', {
  22. 22 id,
  23. 23 });
  24. 24 // ok
  25. 25 this.ctx.success(item);
  26. 26}

model对象

model对象对ctx.db进行了进一步封装,可以便利的支持多实例软删除

  1. 多实例:自动将ctx.instance.id注入到ctx.db相关方法的参数中
  2. 软删除:自动将modeldelete方法修改为update方法,并将数据表的deleted字段从0修改为1

1. 定义model对象

src/suite-vendor/test-party/modules/test-party/backend/src/model/party.js

  1. 1module.exports = app => {
  2. 2 class Party extends app.meta.Model {
  3. 3 constructor(ctx) {
  4. 4 super(ctx, { table: 'testParty', options: { disableDeleted: false } });
  5. 5 }
  6. 6 }
  7. 7 return Party;
  8. 8};
名称 默认值 说明
table model对象对应的数据表名,也可以是视图名
disableDeleted false 是否禁用软删除特性

2. 注册model对象

为了支持业务模块的编译特性,便于Webpack打包,所有对象都需要显式require,model对象也不例外

src/suite-vendor/test-party/modules/test-party/backend/src/models.js

  1. 1const party = require('./model/party.js');
  2. 2
  3. 3module.exports = app => {
  4. 4 const models = {
  5. 5 party,
  6. 6 };
  7. 7 return models;
  8. 8};

3. 使用model对象

我们看看使用model对象如何实现同样的增删改查等操作

  1. 1async echo7() {
  2. 2 // testParty: insert/udpate/delete/get
  3. 3
  4. 4 // insert
  5. 5 const res = await this.ctx.model.party.insert({ personCount: 3 });
  6. 6 const id = res.insertId;
  7. 7 // update
  8. 8 await this.ctx.model.party.update({ id, personCount: 6 });
  9. 9 // get
  10. 10 const item = await this.ctx.model.party.get({ id });
  11. 11 // delete
  12. 12 await this.ctx.model.party.delete({ id });
  13. 13 // ok
  14. 14 this.ctx.success(item);
  15. 15}