#本文章仅用于记录本人学习过程,当作笔记来用,如有侵权请及时告知,谢谢!
首先可以看到这个小程序运用了三个云函数:
首先是createlog
index.js
//创建一个云函数createlog,在cloud/createlog/index.js文件中,实现往logs数据表中插入一条记录的功能
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
try{
return await db.collection('logs').add({
//event是从前端传递过来的参数对象,我们后面会在pages/index/index.js文件中的addLog方法中调用云函数createlog时,传递add、date、openid这些参数
data:{
add: event.add,
date:event.date,
openid:event.openid
}
})
}catch(e){
//插入数据错误
console.log(e)
}
}
package.json
{
"name": "createlog",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"wx-server-sdk": "latest"
}
}
getlogs
index.js
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
try{
//需要从云端传递openid字段,通过openid字段来获取日志信息
return await db.collection('logs').where({
openid: event.openid
}).get()
}catch(e){
//插入数据错误
console.log(e)
}
}
package.json
{
"name": "getlogs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"wx-server-sdk": "latest"
}
}
login
index.js
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
//打开index.js文件,默认帮我们写了一些代码,前面两行代码是每个云函数文件中必有的SDK插件是http请求处理插件,然后再init初始化
// 云函数入口函数
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
return {
openid: wxContext.OPENID
}
}
//云函数修改好了之后,一定要右键点击云函数,选择创建并部署(或者上传并部署)出现部署成功的弹窗,修改才会生效
package.json
{
"name": "login",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"wx-server-sdk": "latest"
}
}