一開始初始化的界面
// 雲函數入口檔案
const cloud = require('wx-server-sdk')
cloud.init()
// 雲函數入口函數
exports.main = async (event, context) => {}
使用
tcb-router + request-promise
将資料請求轉換為
async
,
await
風格。
// 雲函數入口檔案
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')
const rp = require('request-promise')
cloud.init()
// 雲函數入口函數
exports.main = async (event, context) => {
const app = new TcbRouter({
event
})
app.router('playlist', async (ctx, next) => {
// ...
})
return app.serve()
}
定義路由名稱,就可以開始操作資料庫了。
cloud.database().collection('playlist')
在雲資料庫中集合的名稱
app.router('playlist', async (ctx, next) => {
ctx.body = await cloud.database().collection('playlist')
.skip(event.start)
.limit(event.count)
.orderBy('createTime', 'desc')
.get()
.then((res) => {
return res
})
})
或者可以使用 URL 擷取外部的資料。
app.router('lyric', async (ctx, next) => {
ctx.body = await rp(BASE_URL + 'lyric?id=' + parseInt(event.musicId)).then((res) => {
return res
})
})
使用編寫的雲函數
溫馨提示:每次修改都應該重新部署
wx.cloud.callFunction({
name: 'music',
data: {
playlistId: options.playlistId,
$url: 'musiclist'
}
}).then((res) => {
console.log(res)
})