跳到主要内容

微信云开发

云开发核心技术

云开发主要包含三大核心技术

  • 云数据库:
    • 提供在小程序端直接对数据库进行增删改查的能力
    • 数据库是类似于MongoDB的文档存储的数据库,操作非常方便
  • 云存储:
    • 可以在小程序端直接上传、下载、删除文件
    • 自带CDN,提高文件访问速度
    • 可以获取临时链接,支持在小程序外访问
  • 云函数:
    • 提供了在服务器代码的执行能力
    • 包含微信天然的私有鉴权
    • 更大权限的操作数据库等
    • 进行云调用、HTTP请求等操作

初始化

  • 在小程序端开始使用云能力前,需先调用wx.cloud.init方法完成云能力初始化【在app.js中修改,onLaunch】

    • onLaunch: function () {
      //判断是否支持
      if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
      } else {
      wx.cloud.init({
      // env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
      env: 'learn-7gl809ov5d11431a',
      // 是否跟踪用户访问数据,一般开启
      traceUser: true,
      });
      }

      this.globalData = {};
      }

云数据库

  • 我们通过代码增加的时候,会有用户的身份唯一表示openid,可以判断是哪个用户操作的
  • studentCol.doc("2cc84e26642e9b5607947a0111fa54b1")会明确拿到某个数据
  • where模糊
    • eq:等于
    • neq:不等于
    • lt:小于
    • lte:小于等于
    • gt:大于
    • gte:大于等于
    • in:字段值在给定数组里
    • nin:字段值不在给定数组里

步骤:会将第一步第二步放在全局中

// 1.获取到对应的数据库
const db = wx.cloud.database() //拿到我们开始初始化的数据库

// 2.获取到我们要操作的集合
const studentCol = db.collection("students")

// 3.对集合进行操作 —— 增删改查

// 调用方法studentCol.add,穿肚data数据
// 回调函数success返回我们添加成功的id
studentCol.add({
data: {
name: 'one',
age: '19'
},
success(e){
console.log(e);
}
})

//除了用success,还可以用promise的方式 .then

// 1.明确删除哪个数据 - 添加id
// 回调函数显示是否删除成功
studentCol.doc("2cc84e26642e9b5607947a0111fa54b1").remove().then( res =>{
console.log(res);
})



// 2.根据条件查询到数据的结果,将对应的数据都删掉
studentCol.where({
// 明确删除一个数据
name : "one"
}).remove().then( res =>{
console.log(res);
})

studentCol.where({
// 满足条件的:年龄大于25(使用查询指令 db.command)
age: db.command.gt(25)
}).remove().then( res =>{
console.log(res);
})

  • 两种方式
    • update:更新(增加)某一个字段
    • set:使用新对象替换原对象
  • 更新一条数据
// update方式:仅仅改了age的数据
studentCol.doc("2cc84e26642e9b5607947a0111fa54b1").update({
data: {
age: 20
},
success(e){
console.log(e);
}
})

// set方式:将整个对象改成只有一个age
studentCol.doc("2cc84e26642e9b5607947a0111fa54b1").set({
data: {
age: 20
},
success(e){
console.log(e);
}
})
  • 更新多条数据
studentCol.where({
// 满足条件的:年龄大于25(使用查询指令 db.command)
age: db.command.gt(25)
}).update({
data: {
age: 20
},
success(e){
console.log(e);
}
})

  • 方式一:通过id去查(使用doc查询id)

    • studentCol.doc("2cc84e26642e9b5607947a0111fa54b1").get().then( res =>{
      console.log(res.data)
      })
  • 方式二:根据条件(使用where)

    • studentCol.where({
      // 满足条件的:年龄大于25(使用查询指令 db.command)
      age: db.command.gt(25)
      }).get().then( res =>{
      console.log(res.data)
      })
  • 方式三:通过指令过滤数据(使用db.command的指令)

    • studentCol.where({
      // 满足条件的:年龄大于25(使用查询指令 db.command)
      age: db.command.gt(25)
      }).get().then( res =>{
      console.log(res.data)
      })
  • 方式四:正则表达式

  • 方式五:获取整个集合(小程序端一次性最多20条,云函数中可以获取100条)

    • studentCol.get().then( res =>{
      console.log(res.data)
      })
  • 方式六:过滤、分页、排序查询数据(使用field(多虑)、skip(跳过多少条数据)、limit(需要多少数据)、orderBy(排序))

    • //跳过0条数据,取5条数据:取0-4的数据
      studentCol.skip(0).limit(5).get().then( res =>{
      console.log(res.data)
      })

      //跳过5条数据,取5条数据:取5-9的数据
      studentCol.skip(5).limit(5).get().then( res =>{
      console.log(res.data)
      })
    • //orderBy:第一个参数是你根据什么进行排序,第二个参数是要升序还是降序,asc升序,desc降序
      studentCol.skip(5).limit(5).orderBy("age","asc").get().then( res =>{
      console.log(res.data)
      })
    • //返回数据就_id、name、age
      studentCol.field({
      _id:true,
      name:true,
      age:true
      }).skip(5).limit(5).orderBy("age","asc").get().then( res =>{
      console.log(res.data)
      })

云存储

  • 云存储用于将文件存储到云端:
    • 云存储提供高可用、高稳定、强安全的云端存储服务
    • 持任意数量和形式的非结构化数据存储,如视频和图片
    • 并在控制台进行可视化管理;
  • 云存储常见的操作:
    • 上传文件到云存储中(图片、视频、音频等等都可以)
    • 获取文件的临时链接(在外网可以访问)
    • 下载文件到本地(本地文件缓存)
    • 将云存储中的文件删除

上传

先获取资源,比如图片的本地链接

const uploadRes = await wx.cloud.uploadFile({//函数也要加async
filePath: imagePath,//文件本地路径
cloudPath: "",//文件的名字,下面专门来说一下这个文件名字
})
console.log(uploadRes)

// 文件名字我们一般动态拼接,不写死,并且文件名字不写上传会错误
// 一般我们拼接会使用 时间戳+openid
const time = new Date().getTime()
const openid = ''
const extension = imagePath.split(".").pop() ,//文件后缀名,也不能写死

// 所有我们一般设置的文件名是:
const imageName = `${time}_${openid}.${extension}`
// 如果我们不想放到根目录,放到指定文件夹下
wx.cloud.uploadFile({
filePath: imagePath,
cloudPath: "xjn/" + imageName,//放到文件夹xjn下,前面不需要 /
})

下载

async download(){
const res = await wx.cloud.downloadFile({
fileId: "",//用fileId
})
console.log(res)
}

删除

async delete(){
const res = await wx.cloud.deleteFile({
fileList:[
"",//fileId,且必须要使用数组
]
})
console.log(res)
}

获取临时链接

  • 为什么要获取临时链接?

    • 我们将文件上传到云存储后,可以通过filelD在小程序中直接访问;
    • 但是,如果我们希望在小程序以外的地方访问(比如浏览器、手机端),那么fileID是不可以的
    • 这个时候,我们可以通过获取临时链接,该链接可以在小程序以外访问
  • async getFileTap(){
    const res = await wx.cloud.getTempFileURL({
    fileList:[
    "",//fileId,且必须要使用数组
    ]
    })
    console.log(res)
    }
  • 临时链接有效期两个小时

云函数

云函数的使用过程

  • 1.创建一个云函数

  • ⒉编写云函数的代码逻辑

    • // 云函数入口文件
      const cloud = require('wx-server-sdk')

      cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

      // 云函数入口函数
      exports.main = async (event, context) => {
      return "hhh"
      }
  • 3.将云函数上传到云端

  • 4.小程序中对云函数调用

    • //调用wx.cloud.callFunction方法
      // name是指我们要调用哪个云函数
      // 返回值是一个promise,可以用then、success、async await
      wx.cloud.callFunction({
      name:"test"
      }).then(res =>{
      console.log(res.result);
      })

原函数参数的传递

// 调用
wx.cloud.callFunction({
name:"test",
data: {
num1:num1,//增强写法直接写num1
num2:num2
}
}).then(res =>{
console.log(res.result);
})


// 获取
exports.main = async (event, context) => {
let num1 = event.num1
let num2 = event.num2
// const { num1, num2 } = event
return num1 + num2
}

获取openid

// 默认给我们创建的模板就会返回
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
console.log(wxContext);
return {
event,
openid: wxContext.OPENID,//openid
appid: wxContext.APPID,
unionid: wxContext.UNIONID,
}
}

操作数据库

和云数据库操作一样,记得return

发送http请求

使用axios【npm install axios】,使用async和await

云开发使用总结

//js调用云函数,data是参数,name是云函数的名字
wx.cloud.callFunction({
name:"login",
data:{
username,
password
}
}).then(res =>{
console.log(res.result);
})

//云函数调用云数据库:event是调运函数传来的参数都在这里面
exports.main = async (event, context) => {
const { info } = event
console.log(info);
//基本配置,其中没有wx.
const db = cloud.database()
//哪个数据库
const data = db.collection("data")
//添加操作
data.add({
data:{
info
}
})
//返回值
return "111"
}