云函数与微信云函数基本一致
参考:https://blog.csdn.net/weixin_43512977/article/details/124579654
项目:https://blog.csdn.net/weixin_43512977/article/details/124739811
云对象 article
参数与微信云有略微差别
官方文档
// 快捷键 cdb
const db = uniCloud.database()
const _ = db.command
const uniID = require('uni-id')
module.exports = {
// 预处理 _before 一般用于拦截器、统一的身份验证、参数校验等。
_before() {
// 获取客户端信息
const clientInfo = this.getClientInfo()
this.uniID = uniID.createInstance({ // 创建uni-id实例,其上方法同uniID
clientInfo
})
// 获取 token 缓存字段必须是 uni_id_token
const token = this.getUniIdToken()
// 获取方法名
const methodName = this.getMethodName()
// 获取参数 []
const params = this.getParams()
},
// 后处理 _after 用来再加工处理本次调用方法的返回结果或者抛出的错误
// 可以不写。如果写了 _after 那么就要 return result 否则接收不到信息
_after(error, result) {
console.log('error', error);
console.log('result', result);
if (error) {
throw error // 如果方法抛出错误,也直接抛出不处理
}
return result
},
// 添加
async add() {
try {
await db.collection('test').add({
name: 'zs',
age: 25
})
} catch (e) {
console.log(e);
}
},
// 查
async get() {
try {
const res = await db.collection('test').doc('627be34fc2b3040001c20f43').get()
console.log(res);
} catch (e) {
//TODO handle the exception
}
},
// 更新 无则创建
async update() {
try {
// const res = await db.collection('test').doc('627be34fc2b3040001c20f43').update({
// age: 28,
// sex: 2
// })
// 更新并返回新的值
const res = await db.collection('test').doc('627be34fc2b3040001c20f43').updateAndReturn({
age: 28,
sex: 0
})
console.log(28, res);
} catch (e) {
//TODO handle the exception
}
},
// 删除
async remove() {
try {
await db.collection('test').doc('627be3172319ec00015e5a07').remove()
} catch (e) {
//TODO handle the exception
}
}
}
使用
从HBuilderX 3.4.6起,调用云对象的方法时,默认会自动显示交互/提示界面。(当errCode != 0 时触发)
// 导入云对象
const article = uniCloud.importObject('article', {
// customUI: true, // 取消自动展示的交互提示界面
loadingOptions: { // loading相关配置
title: '加载中...', // 显示的loading内的提示文字。默认值为:加载中...
mask: true // 是否使用透明遮罩,配置为true时不可点击页面其他内容。默认值为:true
},
errorOptions: { // 错误界面相关配置
type: 'modal', // 错误信息展示方式,可取值:modal(弹框,默认)、toast(toast消息框)。默认值为:modal
retry: false // 是否展示重试按钮,仅在type为modal时生效。用户点击重试按钮时将重新请求调用的方法,默认为false
}
})
// 调用
article.get()