微信小程序云开发数据库脚手架
发布于 4 年前 作者 xiuying76 3122 次浏览 来自 分享

介绍

1、封装、简化、模型化数据库操作
2、支持查看执行的sql语句

基础库

大于2.8.1

代码片段DEMO

小程序demo: https://developers.weixin.qq.com/s/oXiGFFmI7mia
说明文档: https://www.yuque.com/docs/share/80cbef90-f262-4d2a-b245-079bc462d5e3

如何使用

一、小程序端
1、下载wx-cloud-db-falsework
npm i wx-cloud-db-falsework
2、将wx-cloud-db-falsework.min.js拷贝到小程序项目中,如小程序根目录下的lib文件夹内

3、在app.js中引入wx-cloud-db-falsework.min.js,使用重写过的Page,和原生Page一致,只是增加了use属性

// 根目录/app.js
import { page } from './lib/wx-cloud-db-falsework.min'
Page = page

App({
  onLaunch: function () {}
}

4、创建模型,如: Order,根目录/model/order.js,集合名,默认为model名,首字母会强制小写

// 根目录/model/order.js
import { Model, Controller } from '../lib/wx-cloud-db-falsework.min'

class Order extends Model {
  constructor(o) {
    let t = super(o)
    return t
  }
}
// collectionName 集合名,默认为model名,如Order默认为order,首字母会小写
// collectionKey  集合主键,默认_id
const Odr = Order.init({ env: '环境ID', cloud: wx.cloud [, collectionName = '集合名称', , collectionKey = '主键字段名'] })

export { Odr as Order, Controller }

5、创建控制器,如: Order的controller,根目录/controller/order.js

// 根目录/controller/order.js
import { Order, Controller as Base } from '../model/order'

class Controller extends Base {
    constructor(o){
        super(o)
    }
  	// 在控制器里可以自己封装一些业务功能方法
    getById(id){
        return Order.find(id)
    }
}
let controller = new Controller(Order)
export { controller }

6、在页面中通过use配置需要使用的控制器,控制器实例会挂载在页面实例上,直接通过 this.控制器实例 即可访问,页面: 根目录/pages/index/index.js

// 根目录/pages/index/index.js
import { DB } from '../../lib/wx-cloud-db-falsework.min'
Page({
  use:{
    Order: require('../../controller/order.js')
  },
  data:{},
  onLoad: async function() {
  	// 直接通过 this.控制器实例 即可访问控制器的封装的方法
    await this.Order.getById(1).then(res=>{
      console.log(res)
      // res 可为 DB.DbError实例 或者 DB.DbRes实例
      // 为DB.DbError实例,表示数据库操作异常
      // 为DB.DbRes实例,表示数据库操作正常,而DB.DbRes又包括了DB.DbResultJson和DB.DbResultArray子实例
      // DB.DbResultJson实例说明结果为JSON对象,DB.DbResultArray实例则说明结果为Array对象
    })
    
    // 页面中也可以通过 this.(控制器实例名+'Md')访问模型的方法
    let row = await this.OrderMd.find('xxxx')
    
    // 页面中也可以通过 this.(控制器实例名+'Dd')访问原生db对象,进行原生操作
    let doc = await this.OrderDb.collection('xxx').doc(xx).get()
  }
}

二、云函数端
1、配置云函数package.json,添加wx-cloud-db-falsework

"dependencies": {
    "wx-cloud-db-falsework": "latest",
    "wx-server-sdk": "^2.1.2"
}

2、配置云函数package.json,添加wx-cloud-db-falsework

const cloud = require('wx-server-sdk')
let { Model, DB } =  require('wx-cloud-db-falsework')

# order模型
class Order extends Model {
  constructor(o) {
    let t = super(o)
    return t
  }
}

exports.main = async (event, context) => {
  const Odr = Order.init({ env: '环境ID', cloud })

  return await Odr.add({ _id: (new Date().getTime())+'add'})
}

数据库操作

添加记录

以上述Order模型为例,在页面中添加记录

// 使用model.add(data)添加记录, data为数据json对象或array对象
// 添加一条记录
let res = await this.OrderMd.add({ a:1, b:2 })
// 返回DbResultJson对象 {_id:'xxxx'}

// 添加多条记录
res = await this.OrderMd.add([{	a:1, b:2 }, { a:3, b:4 }])
// 返回DbResultArray对象 [{_id:'xxxx'},{_id:'xxxx'}]

// 支持原生参数
res = await this.OrderMd.add({ data:{ a:1, b:2 } })
res = await this.OrderMd.add({ data: [{	a:1, b:2 }, { a:3, b:4 }] })

// 支持回调函数
this.OrderMd.add({ data:{ a:1, b:2 }, success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

this.OrderMd.add({ data:[{	a:1, b:2 }, { a:3, b:4 }], success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

删除记录

以上述Order模型为例,在页面中删除记录

// 使用model.remove(where)删除记录, where为删除添加,可为空
// 根据条件删除记录
let res = await this.OrderMd.where({ _id: 'xxx', abc: 123 }).remove()
res = await this.OrderMd.remove({ _id: 'xxx', abc: 123 })
// 根据主键删除
res = await this.OrderMd.doc('xxx').remove()
// 返回DB.DbError对象或DB.DbRes对象 {removed:Number}

// 支持回调函数
this.OrderMd.where({ _id: 'xxx', abc: 123 }).remove({ success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

this.OrderMd.remove({ where:{ _id: 'xxx', abc: 123 }, success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

查询记录

查询一条记录

以上述Order模型为例,在页面中查询记录

// 使用model.find()查询记录
// 根据条件查询记录
let res = await this.OrderMd.where({ _id: 'xxx', abc: this.OrderMd._.eq(123) }).find()
res = await this.OrderMd.find({ _id: 'xxx', abc: this.OrderMd._.eq(123) })
// 根据主键查询记录
res = await this.OrderMd.doc('xxx').find()
res = await this.OrderMd.find('xxx')
// 返回DB.DbError对象或DB.DbRes对象 {_id:'xxx', ....}

// 使用model.where().get()查询记录
// 根据条件查询记录
let res = await this.OrderMd.where({ _id: 'xxx' }).get()
// 返回DB.DbError对象或DB.DbRes对象 [{_id:'xxx', ....}]

// 根据主键查询记录
res = await this.OrderMd.doc('xxx').get()
// 返回DB.DbError对象或DB.DbRes对象 {_id:'xxx', ....}

// 支持回调函数
this.OrderMd.find({ where:{ _id: 'xxx', abc: 123 }, success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

this.OrderMd.where({ _id: 'xxx', abc: 123 }).find({ success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

this.OrderMd.where({ _id: 'xxx' }).get({ success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

this.OrderMd.doc('xxx').get({ success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

特殊支持:

// json字符串条件
let res = await this.OrderMd.find(`{ _id: 'xxx' }`)
res = await this.OrderMd.where(`{ _id: 'xxx' }`).find()
// 使用command时需要加this
res = await this.OrderMd.find(`{ _id: this._.eq('xxx') }`)
res = await this.OrderMd.where(`{ _id: this._.eq('xxx') }`).find()

查询多条记录

// 使用model.findAll()查询记录
// 根据条件查询记录
let res = await this.OrderMd.where({ abc: 'xxx', abc: this.OrderMd._.eq(123) }).findAll()
res = await this.OrderMd.findAll({ abc: 'xxx', abc: this.OrderMd._.eq(123) })
// 返回DB.DbError对象或DB.DbRes对象 [{_id:'xxx', ....}]

// 使用model.where().get()查询记录
// 根据条件查询记录
let res = await this.OrderMd.where({ _id: 'xxx' }).get()
// 返回DB.DbError对象或DB.DbRes对象 [{_id:'xxx', ....}]

// 支持回调函数
this.OrderMd.findAll({ where:{ abc: 'xxx' }, success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

this.OrderMd.where({ abc: 'xxx' }).findAll({ success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

this.OrderMd.where({ _id: 'xxx' }).get({ success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

this.OrderMd.doc('xxx').get({ success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

特殊支持:

// json字符串条件
let res = await this.OrderMd.findAll(`{ abc: 'xxx' }`)
res = await this.OrderMd.where(`{ abc: 'xxx' }`).findAll()
// 使用command时需要加this
res = await this.OrderMd.findAll(`{ abc: this._.eq('xxx') }`)
res = await this.OrderMd.where(`{ abc: this._.eq('xxx') }`).findAll()

更新记录

以上述Order模型为例,在页面中查询记录

// 使用model.update()更新记录
// 根据条件更新记录
let res = await this.OrderMd.where({ _id: 'xxx', abc: this.OrderMd._.eq(123) }).update({ cde: 456 })
res = await this.OrderMd.update({ cde: 456 }, { _id: 'xxx', abc: this.OrderMd._.eq(123) })
// 根据主键更新记录
res = await this.OrderMd.doc('xxx').update({ cde: 456 })
// 返回DB.DbError对象或DB.DbRes对象 {updated:Number}

// 支持回调函数
this.OrderMd.where({ _id: 'xxx', abc: this.OrderMd._.eq(123) }).update({ data:{ cde: 456 }, success(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
}, fail(e){
	// e 为 DB.DbError实例
}, complete(r){
  // r 为 DB.DbError实例 或者 DB.DbRes实例
} })

聚合操作

以上述Order模型为例,在页面中查询记录

// 使用model.aggregate()开始聚合操作
let res = await this.OrderMd.aggregate()
.addFields({
    test: 1
})
.match({
    test: 1
})
... // 其他聚合操作
.end()
// 返回DB.DbError对象或DB.DbRes对象 [{_id:'xxx', ....}, ...]

数据监听

以上述Order模型为例,在页面中查询记录

// 使用model.wcthis(ops)监听记录,
let res = await this.OrderMd.wcthis({
	onChange(res){
  		// 监听操作
  	},
	onError(err){
  		// 监听出错
 	}
}).where({ _id: 'xxx' }).update({ cde: 456 })

// 使用原生watch方法监听记录,
await this.OrderMd.where({ _id: 'xxx' }).watch({
	onChange(res){
  		// 监听操作
 	},
 	onError(err){
  		// 监听出错
 	}
})
let res = this.OrderMd.where({ _id: 'xxx' }).update({ cde: 456 })

数据库操作结果

数据库操作结果返回 DB.DbError实例 或者 DB.DbRes实例

add结果

res = model.add(…) 添加一条数据返回 { _id: ‘xxx’ } ,添加多条时返回 [{ _id: ‘xxx’ }, { _id: ‘xxx’ }]
返回的结果可以直接调用update,remove方法,如:

// 添加一条记录
let res = await this.OrderMd.add({ a:1, b:2 })
// 返回DbResultJson对象 {_id:'xxxx'}
if(res instanceof DB.DbRes){
  // 更新操作,更新刚新增的这条记录
  let back = res.update({c: 555})
  // 删除操作,删除刚新增的这条记录
  back = res.remove()
}

// 添加多条记录
res = await this.OrderMd.add([{	a:1, b:2 }, { a:3, b:4 }])
// 返回DbResultArray对象 [{_id:'xxxx'},{_id:'xxxx'}]
if(res instanceof DB.DbRes){
  // 更新操作,更新刚新增的这几条记录
  let back = res.update({c: 555})
  // 删除操作,删除刚新增的这几条记录
  back = res.remove()
}

remove结果

res = model.remove() 删除记录返回 { removed:Number }

// 删除记录
let res = await this.OrderMd.remove({ a:1, b:2 })
// 返回DbResultJson对象 {removed:Number}
if(res instanceof DB.DbRes){
  	if(res.removed){
  		// 删除成功
	}else{
  		// 删除失败
  	}
}else{
  consloe.errr(res)
}

find/findAll/get结果

res = model.find() 返回 { _id: ‘xxx’, … }
res = model.findAll/get() 返回 [{ _id: ‘xxx’, … }, { _id: ‘xxx’, … }, …]
返回的结果可以直接调用update,remove方法,如:

// 添加一条记录
let res = await this.OrderMd.doc('xxx').find()
// 返回DbResultJson对象 {_id:'xxxx'}
if(res instanceof DB.DbRes){
  // 更新操作,更新这条记录
  // let back = res.update({c: 555})
  
  // 删除操作,删除这条记录
  let back = res.remove()
}

// 添加多条记录
res = await this.OrderMd.where({abc:123}).findAll()
res = await this.OrderMd.where({abc:123}).get()
// 返回DbResultArray对象 [{ _id: 'xxx', ... }, { _id: 'xxx', ... }, ...]
if(res instanceof DB.DbRes){
  // 更新操作,更新这几条记录
  // let back = res.update({c: 555})
  // 删除操作,删除这几条记录
  let back = res.remove()
}

update结果

res = model.update() 更新数据返回 { updated: Number }

// 更新记录
let res = await this.OrderMd.where({ a:1, b:2 }).update({c:555})
res = await this.OrderMd.doc('xxx').update({c:555})
// 返回DbResultJson对象 {update:Number}
if(res instanceof DB.DbRes){
  	if(res.update){
  		// 更新成功
	}else{
  		// 更新失败
  	}
}else{
  consloe.errr(res)
}

查看SQL语句

以上述Order模型为例,在页面中查询记录
数据库操作结果返回 DB.DbRes 对象时,可查看执行的SQL语句

var res = await this.OrderMd.add({ a:1, b:2 })
console.log(res.sql)

var res = await this.OrderMd.remove({ a:1, b:2 })
console.log(res.sql)

var res = await this.OrderMd.doc('xxx').find()
console.log(res.sql)

var res = await this.OrderMd.where({ a:1, b:2 }).update({c:555})
console.log(res.sql)

var res = await this.OrderMd.aggregate()
.addFields({
    	test: 1
})
.match({
    test: 1
})
.end()
console.log(res.sql)

ps: 可以拿去练练手,不保证无BUG

回到顶部