微信小程序云开发比较适用于简单的业务场景,简单上手快
云函数-查
tip: 查询接口每次最多返回100条数据,需要分批次请求获取全部数据
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const MAX_LIMIT = 100
const dbName = 'hotels'
exports.main = async (event, context) => {
// 先取出集合记录总数
const countResult = await db.collection(dbName).count()
const total = countResult.total
const inputValue = event.inputValue || ''
const city = event.city || ''
const _ = db.command
// 计算需分几次取
const batchTimes = Math.ceil(total / 100)
// 承载所有读操作的 promise 的数组
const tasks = []
for (let i = 0; i < batchTimes; i++) {
const promise = db.collection(dbName).skip(i * MAX_LIMIT).limit(MAX_LIMIT).orderBy('createTime', 'desc').where(_.and([
{
ad_info: db.RegExp({
regexp: '.*' + inputValue, //模糊匹配
options: 'i',
})
},
{
city: db.RegExp({
regexp: '.*' + city, //模糊匹配
options: 'i',
})
},
])).get()
tasks.push(promise)
}
// 等待所有
return (await Promise.all(tasks)).reduce((acc, cur) => {
return {
data: acc.data.concat(cur.data),
errMsg: acc.errMsg,
}
})
}
删
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
const dbName = 'hotels'
return db.collection(dbName).doc(event.id).remove()
}
改
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
const dbName = 'hotels'
return db.collection(dbName).doc(event.id).update({
data: {
// key: value
}
})
}
增
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
const dbName = 'hotels'
return db.collection(dbName).add({
data: {
// key: value
}
})
}
图片文件上传存储
tip: 文件上传成功,返回的是tempFilePaths是临时链接,可以存储fileID,通过getTempFileURL方法,根据fileID参数来获取图片地址
uploadImg () {
const self = this
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success (chooseResult) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = chooseResult.tempFilePaths[0]
self.setData({
tempFilePaths: tempFilePaths
})
// 将图片上传至云存储空间
const cloudPath = `cloudbase/hotels/${Date.now()}-${Math.floor(Math.random(0, 1) * 1000)}` + tempFilePaths.match(/\.[^.]+?$/)
wx.cloud.uploadFile({
// 指定上传到的云路径
cloudPath: cloudPath,
// 指定要上传的文件的小程序临时文件路径
filePath: tempFilePaths,
success: res => {
wx.showToast({
title: '上传成功',
icon: 'success',
duration: 2000
})
self.setData({
fileID: res.fileID
})
},
})
}
})
},
图片文件根据fileID获取链接
tip: 接口一次最多获取50条数据,需要分批次请求
async getImgList (fileList) {
let total = fileList.length
if (total) {
const batchTimes = Math.ceil(total / 50)
const tasks = []
for (let i = 0; i < batchTimes; i++) {
const promise = wx.cloud.getTempFileURL({
fileList: fileList
})
tasks.push(promise)
}
return (await Promise.all(tasks)).reduce((acc, cur) => {
return {
data: acc.data.concat(cur.data),
errMsg: acc.errMsg,
}
})
}
}
let fileList = [fileID, fileID, ...]
this.getImgList(fileList).then(res => {
let list = res.fileList
// 取list中的tempFileURL即可获取图片链接
})
删除文件
tip: 根据fileID来删除云存储中的文件资源,可批量删除
let fileList = [fileID, fileID, ...]
if (fileList?.length) {
wx.cloud.deleteFile({
fileList: fileList
})
}
云函数调用示例
let info ={ fileID: '' }
wx.cloud.callFunction({
name: 'update',
data: {
id: this.data.id,
params: {
fileID: info.fileID
// key: value
}
}
}).then(res => {
wx.showToast({
title: '保存成功',
icon: 'success',
duration: 2000
})
wx.navigateBack()
})