云函数获取数据实现
发布于 1 年前 作者 guiying79 325 次浏览 来自 分享

建立环境

首先需要在project.config.json 文件,新增 cloudfunctionRoot 字段

{

“cloudfunctionRoot”: “cloudfunctions/”

}

右键当前环境,选择新建 Node.js 函数,这里我们将云函数命名为 get_lists_functions

可以看到其内部有一个模板
// 云函数入口文件
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

// 获取openId云函数入口函数
exports.main = async (event, context) => {
  // 获取基础信息
  let _db = cloud.database();
  const countResult = await _db.collection('GridNotes').count()
  const total = countResult.total
  const count = Math.ceil(total / 5)
  if(count < event.skip) {
    return {
      code : -1,
      result : null
    }
  }
    const tasks = []
    let opts = {
      "_openid" : event.openid
    }
    if(event.keyword) {
      opts = {
        '_openid': event.openid,
          'content': {
           $regex: ".*" + event.keyword + ".*"
         }
      }
    } 

    const promise = _db.collection('GridNotes').where(opts).orderBy('times', 'desc').skip(event.skip * 5).limit(5).get()
    tasks.push(promise)

  // 等待所有
  return  { 
    code : 0,
    result : (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg
    }
  })
  }
};

以上 exports.main = async (event, context) 中event 对象中含有——调用时传输的参数、openid、keyword

小程序中调用云函数

如何在js中调用云函数:

wx.cloud.callFunction({
  // 云函数名称
  name: 'get_lists_functions', 
  // 传给云函数的参数
  data: {
	 openid : openid,
         skip : 0

  },
  success: function(res) {
    console.log(res.result.new_name) // hello world !!!
  },
  fail: console.error
})

云函数中的接收参数

在云函数中接收js传来的参数,并返回参数:

exports.main = async (event, context) => {
  return {
    new_name: "hello " + event.name  // 接收来自js的参数name,返回新的返回值new_name
  }
}

记得写好云函数后,要记得上传哦!(右键函数,选择上传并部署:云端安装依赖)

总结

好了,到现在的我们,我们完成了云函数与小程序的参数传递,小程序调用函数wx.cloud.callFunction,把参数 name 写道data中,将数据传到云函数 todo_functions,接着云函数通过event接收到来在小程序的参数,event.name可以获取到参数,接着小程序通过success,可以接收到云函数成功调用后返回的new_name, res.result.new_name。


回到顶部