今天我们就来说说如何使用了云函数,云数据库,云存储
一:如何使用云函数,需要哪些步骤
1:node环境是必不可少的,网上有很多教程可以自己学习看下如何安装
2:新建一个云函数模板,在cloudfunctions目录底下,新建一个云函数的文件getAllShopData。(右键,新建node.js云函数)
leizhenzi
3:在新建文件上右击文件,选择在终端打开
4:在cmd 打开云函数目录中,安装依赖。
leizhenzi
5:请求网络,所以要安装请求网络的库,请求网络的库可以使用node.js中的request库
npm install --save request
npm install --save request-promise
leizhenzi
6:依赖已经放置在package.json文件之中了
{
"name" : "miniprogram" ,
"version" : "1.0.0" ,
"description" : "" ,
"main" : "app.js" ,
"scripts" : {
"test" : "echo \"Error: no test specified\" && exit 1"
},
"keywords" : [],
"author" : "" ,
"license" : "ISC" ,
"dependencies" : {
"vant-weapp" : "^0.5.27"
}
}
二:如何使用云数据库
三:如何使用云存储
1: 我们发布商品时候,需要用到图片,需要把图片上传,这时候就需要用到云存储了
2:我们在存储那里新建一个存放图片的目录ShowDataImg
雷阵子
3:上传调用方法如下,主要文件存储目录名字ShowDataImg一样
var num = 0
for (var i = 0; i < upImgList.length; i++) {
var timestamp = 'A' + i + 'A' + +new Date().getTime()
const cloudPath = 'shopDataImg/' + timestamp + upImgList[i].match(/\.[^.]+?$/)[0]
wx.cloud.uploadFile({
cloudPath: cloudPath,
filePath: upImgList[i], // 文件路径
}).then(res => {
}).catch(error => { })
}
四:如何使用云函数增删改查
1:云函数增加调用,我们前面发布商品时候已经使用过了。
2:云函数删除使用
wx.showModal({
title: '提示' ,
content: '确定删除此商品' ,
success(res) {
if (res.confirm) {
const db = wx.cloud.database()
db.collection('shopData' ).doc(e.currentTarget.dataset.id).remove().then(res => {
console.log(res)
wx.showToast({
title: '删除成功' ,
icon: 'none'
})
})
}
}
})
var that = this
const db = wx.cloud.database()
db.collection('staticData' ).doc("ee3099285ccd892d0bfec45b2629338d" ).update({
data: {
notice: that.data.notice
}
}).then(res => {
if (res.stats.updated === 1) {
wx.showToast({
title: '更新成功' ,
icon: 'none'
})
that.getNotice()
}
})
var that = this
const db = wx.cloud.database()
db.collection('staticData' ).doc("4e4b1a80-9315-4c42-9cd2-f92fb1578497" ).get().then(res => {
console.log(res.data.notice)
that.setData({
notice: res.data.notice
})
})
五:如何写云函数
// 云函数入口文件
const cloud = require('wx-server-sdk' )
cloud.init()
// 云函数入口函数
const db = cloud.database()
const MAX_LIMIT = 100
exports.main = async (event, context) => {
// 先取出集合记录总数
const countResult = await db.collection('shopData' ).count()
const total = countResult.total
// 计算需分几次取
const batchTimes = Math.ceil(total / 100)
// 承载所有读操作的 promise 的数组
const tasks = []
for (let i = 0; i < batchTimes; i++) {
const promise = db.collection('shopData' ).skip(i * MAX_LIMIT).limit(MAX_LIMIT).where({
isOnline: true
}).get()
tasks.push(promise)
}
// 等待所有
return (await Promise.all(tasks)).reduce((acc, cur) => ({
data: acc.data.concat(cur.data),
errMsg: acc.errMsg,
}))
}
onShow: function () {
var that = this
that.getNotice()
wx.cloud.callFunction({
name: 'getAllShopData'
}).then(res => {
that.setData({
shopData: res.result.data
})
})
},
(ps:有些代码是截图的,可能会复制不了,最后我会上传到github ,你可以把代码下载下来哈哈哈,欢迎关注我的公众号 。。。)