云对象模板
1 // 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj 2 // jsdoc语法提示教程:https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129 3 module.exports = { 4 _before: function() { // 通用预处理器 5 // 连接数据库代码 6 const db = uniCloud.databaseForJQL({ 7 clientInfo: this.getClientInfo() 8 }) 9 10 const methodName = this.getMethodName() //获取当前请求的函数名称 11 // 如果当前执行的是 method1函数,但是用户未登陆时,报错 12 if (methodName === 'method1' && !this.getUniIdToken()) { 13 throw new Error('token不存在') 14 } 15 }, 16 17 // error 是内置参数 18 // result 是函数返回结果 19 _after(error, result) { 20 if (error) { 21 throw error // 如果方法抛出错误,也直接抛出不处理 22 } 23 result.timeCost = Date.now() - this.startTime 24 return result 25 }, 26 27 // 定时执行时,会调用这里 28 _timing() { 29 30 }, 31 32 /** 33 * method1方法描述 34 * @param {string} param1 参数1描述 35 * @returns {object} 返回值描述 36 */ 37 method1(param1) { 38 // 参数校验,如无参数则不需要 39 if (!param1) { 40 return { 41 errCode: 'PARAM_IS_NULL', 42 errMsg: '参数不能为空' 43 } 44 } 45 // 业务逻辑 46 47 // 返回结果 48 return { 49 param1 //请根据实际需要返回值 50 } 51 } 52 }
在云对象的_before预处理内,进行身份验证的方法:
// 如果出现错误:Cannot find module 'uni-id-common' ... 提示时,是因为没有将当前云对象与 uni-id-common建立依赖关系,见下图:

const uniID = require('uni-id-common') module.exports = { _before: async function() { const clientInfo = this.getClientInfo() this.uniID = uniID.createInstance({ clientInfo }) const token = this.getUniIdToken() let payload = await this.uniID.checkToken(token) let role = payload.role||[] //检查是不是管理员,或者自己的云函数调用此云函数 if(clientInfo.source != 'server' && !role.includes('admin')){ return { errCode: 'uni-push-co-permission-denied', errMsg: '你没有访问此接口权限' } } }, ...
注意:如果是在数据库触发器内调用云对象,它是无法获取用户信息!所以 this.getUniIdToken() 即不到值!!!
且数据库触发器调用云对象时,clientInfo.source 的值为 function。
clientInfo.source值类型: function | http | client | server
在_before内分析是否由数据库触发器调用代码:
if(clientInfo.source == 'function' && !token){
// 数据库触发器或服务器端调用(要求将所有可执行操作页面,必须登陆)
}

浙公网安备 33010602011771号