hwj-common-lib
Version:
微信小程序云开发通用模块库,支持灵活的环境配置
125 lines (110 loc) • 2.85 kB
JavaScript
const cloud = require('wx-server-sdk')
const { CLOUD_ENV } = require('./env')
const { BusinessError } = require('./error')
// 初始化云开发环境
cloud.init({
env: CLOUD_ENV
})
// 获取数据库实例
const db = cloud.database()
const _ = db.command
const $ = _.aggregate
// 通用的数据库操作封装
class Database {
constructor(collection) {
this.collection = collection
this.db = db.collection(collection)
}
// 创建文档
async create(data) {
try {
const result = await this.db.add({
data: {
...data,
createTime: db.serverDate(),
updateTime: db.serverDate()
}
})
return result._id
} catch (error) {
throw new BusinessError(`创建${this.collection}记录失败:${error.message}`)
}
}
// 更新文档
async update(id, data) {
try {
await this.db.doc(id).update({
data: {
...data,
updateTime: db.serverDate()
}
})
return true
} catch (error) {
throw new BusinessError(`更新${this.collection}记录失败:${error.message}`)
}
}
// 获取单个文档
async get(id) {
try {
const { data } = await this.db.doc(id).get()
return data
} catch (error) {
throw new BusinessError(`获取${this.collection}记录失败:${error.message}`)
}
}
// 条件查询
async find(query = {}, options = {}) {
try {
let chain = this.db.where(query)
// 排序
if (options.orderBy) {
const [field, direction] = options.orderBy.split(' ')
chain = chain.orderBy(field, direction || 'desc')
}
// 分页
if (options.skip) {
chain = chain.skip(options.skip)
}
if (options.limit) {
chain = chain.limit(options.limit)
}
// 字段选择
if (options.field) {
chain = chain.field(options.field)
}
const { data } = await chain.get()
return data
} catch (error) {
throw new BusinessError(`查询${this.collection}记录失败:${error.message}`)
}
}
// 删除文档
async delete(id) {
try {
await this.db.doc(id).remove()
return true
} catch (error) {
throw new BusinessError(`删除${this.collection}记录失败:${error.message}`)
}
}
// 计数
async count(query = {}) {
try {
const { total } = await this.db.where(query).count()
return total
} catch (error) {
throw new BusinessError(`统计${this.collection}记录失败:${error.message}`)
}
}
// 开启事务
async transaction() {
return await db.startTransaction()
}
}
module.exports = {
db,
_,
$,
Database
}