天天看點

小程式tcb-router雲開發使用

  • tcb-router基于 koa 風格的小程式·雲開發雲函數輕量級類路由庫,主要用于優化服務端函數處理邏輯
  • 基于tcb-router 一個雲函數可以分很多路由來處理業務環境。
  • 一個使用者在一個雲環境隻能建立50個雲函數
  • 相似的請求歸類到同一個函數處理
  • tcb-router

    就相當于koa的中間件

相當于一個洋蔥模型,每一層相當于一個中間件,一層一層執行,隻有最後一個執行完之後,才傳回

小程式tcb-router雲開發使用

request 請求

response 響應

小程式tcb-router雲開發使用

安裝

雲函數入口檔案

cnpm install tcb-router           

在你的雲函數檔案引入

const TcbRouter = require('tcb-router')           

使用方法

exports.main = async (event, context) => {
  const app = new TcbRouter({event})

  // 播放歌曲
  app.router('musicUrl',async(ctx,next) =>{
    ctx.body = await rp(BASE_URL+ `/song/url?id=${event.musicId}`).then((res) =>{
      return res
    })
  })
  // 歌詞
  app.router('lyric', async (ctx, next) => {
    ctx.body = await rp(BASE_URL + `/lyric?id=${event.musicId}`).then((res) => {
      return res
    })
  })
  return app.serve()
}           

就相當與我們使用koa寫接口一樣,定義url接口名稱

使用

在我們需要的檔案調用對應的接口

其中

name

要調用的雲函數名稱,

$url

要調用的路由的路徑

wx.cloud.callFunction({
        name: 'music',
        data: {
          musicId,
          $url: 'lyric'
        }
      }).then((res) =>{
        const lrc = JSON.parse(res.result).lrc
        if(lrc) {
          lyric = lrc.lyric
        }
        this.setData({
          lyric
        })
      })           

以上就是所有的内容,最終效果通路

https://github.com/MrZHLF/wx-music