1. 程式人生 > 實用技巧 >小程式雲開發—簡單blog實現

小程式雲開發—簡單blog實現

tcb-router

基於koa風格的小程式·雲開發雲函式輕量級類路由庫,主要用於優化服務端函式處理

安裝tcb-router

在雲函式當前目錄下安裝:npminstall--savetcb-router

package.json

{
  "name": "blog",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  
"license": "ISC", "dependencies": { "tcb-router": "^1.1.2", "wx-server-sdk": "latest" } }

package-lock.json

{
  "name": "blog",
  "version": "1.0.0",
  "lockfileVersion": 1,
  "requires": true,
  "dependencies": {
    "tcb-router": {
      "version": "1.1.2",
      "resolved": "https://registry.npmjs.org/tcb-router/-/tcb-router-1.1.2.tgz",
      
"integrity": "sha512-VB+83paVdYG0LWaodh73JUy660te2oleM5gETslbCHLnhTtgXXYfAR0dlHBU5dIhhH47V1nKp43lZUo6Xm9O4g==" } } }

雲函式的index.js

 1 // 雲函式入口檔案
 2 const cloud = require('wx-server-sdk')
 3 
 4 cloud.init()
 5 const TcbRouter=require('tcb-router')
 6 const db=cloud.database()
 7 const blogCollection=db.collection('blog')
8 const commentCollection=db.collection('blog-comment') 9 const MAX_LIMIT=100 10 // 雲函式入口函式 11 exports.main = async (event, context) => { 12 const app=new TcbRouter({ 13 event 14 }) 15 //部落格列表 路由 16 app.router('list',async(ctx,next)=>{ 17 //根據關鍵字查詢資料庫 18 const keyword=event.keyword 19 let w = {} 20 if (keyword.trim() != '') { 21 w = { 22 content: new db.RegExp({ 23 regexp: keyword, 24 options: 'i' 25 }) 26 } 27 } 28 let blogList = await blogCollection.where(w) 29 .skip(event.start).limit(event.count) 30 .orderBy('createTime', 'desc').get().then((res) => { 31 // console.log(res); 32 return res.data 33 }) 34 ctx.body = blogList 35 }) 36 // 部落格詳細(內容加評論) 路由 37 app.router('detail', async(ctx, next) => { 38 let blogId = event.blogId 39 // 詳情查詢 40 let detail = await blogCollection.where({ 41 _id: blogId 42 }).get().then((res) => { 43 return res.data 44 }) 45 // 評論查詢 46 const countResult = await commentCollection.count() 47 const total = countResult.total 48 let commentList = { 49 data: [] 50 } 51 if (total > 0) { 52 const batchTimes = Math.ceil(total / MAX_LIMIT) 53 const tasks = [] 54 for (let i = 0; i < batchTimes; i++) { 55 let promise = db.collection('blog-comment').skip(i * MAX_LIMIT) 56 .limit(MAX_LIMIT).where({ 57 blogId 58 }).orderBy('createTime', 'desc').get() 59 tasks.push(promise) 60 } 61 if (tasks.length > 0) { 62 commentList = (await Promise.all(tasks)).reduce((acc, cur) => { 63 return { 64 data: acc.data.concat(cur.data) 65 } 66 }) 67 } 68 69 } 70 ctx.body = { 71 commentList, 72 detail, 73 } 74 }) 75 76 return app.serve() 77 }

blog.js呼叫雲函式

_loadBlogList(start = 0,keyword='') {
    wx.cloud.callFunction({
      name: 'blog',
      data: {
        keyword,
        start,
        count: 10,
        $url: 'list',
      }
    }).then((res) => {
      // console.log(res)
      this.setData({
        blogList: this.data.blogList.concat(res.result)
      })
    })
  },

blog-comment.js 呼叫雲函式

 _getBlogDetail() {
    wx.showLoading({
      title: '載入中',
      mask: true,
    })

    wx.cloud.callFunction({
      name: 'blog',
      data: {
        blogId: this.data.blogId,
        $url: 'detail',
      }
    }).then((res) => {
      console.log(res);
      let commentList = res.result.commentList.data
      commentList.forEach(element => {
        element.createTime = formatTime({date:new Date(element.createTime)})
      });

      this.setData({
        commentList,
        blog: res.result.detail[0],
      })

      wx.hideLoading()
      // console.log(res)
    })
  },