跳至主要內容

云开发

Emilia Zhen大约 3 分钟wechat

云开发

  1. 在根目录新建文件夹cloudfunctions
  2. project.config.json中添加
"cloudfunctionRoot": "cloudfunctions/",
  1. app.jsonLaunch下初始化
if (!wx.cloud) {
  console.error('请使用 2.2.3 或以上的基础库以使用云能力')
} else {
  wx.cloud.init({
    // env 参数说明:
    //   env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
    //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
    //   如不填则使用默认环境(第一个创建的环境)
    env: 'zhen-fk3dv',
    traceUser: true,
  })
}
  1. cloudfunctions右键,新建Node.js云函数,装好需要的依赖
  2. index.js
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
  return await cloud
    .database()
    .collection('storyList')
    .skip(event.start)
    .limit(event.count)
    .orderBy('time', 'desc')
    .get()
    .then((res) => res)
}
  1. 对云函数文件夹右键,上传并部署,云端安装依赖
  2. pages页面中index.js调用
wx.cloud
  .callFunction({
    name: 'getStoryList',
    data: {
      start: this.data.storyList.length,
      count: 3,
    },
  })
  .then((res) => console.log(res))
  1. 云函数中对应的项点击配置,可以更改超时时间

request-promise

// 云函数入口文件
const cloud = require('wx-server-sdk')
const rp = require('request-promise')
cloud.init()
const db = cloud.database()
const URL = 'http://musicapi.xiecheng.live/personalized'
const storyListCollection = db.collection('storyList')
const MAX_LIMIT = 10
// 云函数入口函数
exports.main = async (event, context) => {
  const countResult = await storyListCollection.count()
  const total = countResult.total
  const batchTimes = Math.ceil(total / MAX_LIMIT)
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    let promise = storyListCollection
      .skip(i * MAX_LIMIT)
      .limit(MAX_LIMIT)
      .get()
    tasks.push(promise)
  }
  let dataList = []
  if (tasks.length > 0) {
    dataList = (await Promise.all(tasks)).reduce((total, current) => total.data.concat(current.data))
  }
  const list = await rp(URL).then((res) => JSON.parse(res).result)
  storyListCollection.add(list)
  console.log(list)
}

定时触发器

  1. 在云函数文件夹下config.json
  "triggers": [
    {
      "name": "myTrigger",
      "type": "timer",
      "config": "0 0 10,14,16,23 * * * *"
    }
  ]
  1. 在云函数文件夹右键,上传触发器

上拉加载下拉刷新

json文件中允许下拉, "enablePullDownRefresh": true

const app = getApp()
const PAGE_SIZE = 5
Page({
  data: {
    storyList: [],
    canReachBottom: true,
  },
  onLoad: function () {
    this.getStoryList()
  },
  onReachBottom() {
    if (this.data.canReachBottom) {
      this.getStoryList()
    }
  },
  onPullDownRefresh() {
    this.setData({
      storyList: [],
    })
    this.getStoryList()
  },
  getStoryList() {
    wx.showLoading({
      title: '加载中...',
    })
    wx.cloud
      .callFunction({
        name: 'getStoryList',
        data: {
          start: this.data.storyList.length,
          count: PAGE_SIZE,
        },
      })
      .then((res) => {
        wx.stopPullDownRefresh()
        wx.hideLoading()
        this.setData({
          canReachBottom: PAGE_SIZE === res.result.data.length,
          storyList: this.data.storyList.concat(res.result.data),
        })
      })
  },
})

tcb-router

云函数安依赖

// 云函数的 index.js
const TcbRouter = require('./router')
exports.main = (event, context) => {
  const app = new TcbRouter({ event })

  // app.use 表示该中间件会适用于所有的路由
  app.use(async (ctx, next) => {
    ctx.data = {}
    await next() // 执行下一中间件
  })
  // 路由为数组表示,该中间件适用于 user 和 timer 两个路由
  app.router(['user', 'timer'], async (ctx, next) => {
    ctx.data.company = 'Tencent'
    await next() // 执行下一中间件
  })
  // 路由为字符串,该中间件只适用于 user 路由
  app.router(
    'user',
    async (ctx, next) => {
      ctx.data.name = 'heyli'
      await next() // 执行下一中间件
    },
    async (ctx, next) => {
      ctx.data.sex = 'male'
      await next() // 执行下一中间件
    },
    async (ctx) => {
      ctx.data.city = 'Foshan'
      // ctx.body 返回数据到小程序端
      ctx.body = { code: 0, data: ctx.data }
    }
  )
  // 路由为字符串,该中间件只适用于 timer 路由
  app.router(
    'timer',
    async (ctx, next) => {
      ctx.data.name = 'flytam'
      await next() // 执行下一中间件
    },
    async (ctx, next) => {
      ctx.data.sex = await new Promise((resolve) => {
        // 等待500ms,再执行下一中间件
        setTimeout(() => {
          resolve('male')
        }, 500)
      })
      await next() // 执行下一中间件
    },
    async (ctx) => {
      ctx.data.city = 'Taishan'
      // ctx.body 返回数据到小程序端
      ctx.body = { code: 0, data: ctx.data }
    }
  )
  return app.serve()
}

在页面调用

// 调用名为 router 的云函数,路由名为 user
wx.cloud.callFunction({
  // 要调用的云函数名称
  name: 'router',
  // 传递给云函数的参数
  data: {
    $url: 'user', // 要调用的路由的路径,传入准确路径或者通配符*
    other: 'xxx',
  },
})