Build mini Forum with Small Program and Cloud Development in Two Days

Keywords: Javascript Database JSON SDK github

I recently dabbled in the knowledge of small programs, so I developed a small program similar to my colleagues over the weekend. I deeply experienced the cloud function, database and storage capabilities provided by the small program cloud development model. For cloud development, refer to the documentation: Small Program Cloud Development.

Personally, the greatest benefit of cloud development is the simplification of authentication process and the weakening of back-end, so people like me who have never been in touch with small program development can develop a product with complete functions and close-loop experience within two days of the weekend.

Finally, this article is not to move official documents, nor will it introduce the development tools and the use of cloud development background in detail, so it is recommended to digest this article together with the document links given above.

functional analysis

At present, the function of this small program is relatively simple (publishing posts, browsing posts, publishing comments). It can be shown by the following chart without further elaboration:

As can be seen from the schematic diagram, the database (posts, comments), storage (pictures), cloud functions (reading, writing, updating databases, etc.) developed in the cloud will be involved, which achieves the purpose of hands-on well.

Publish posts

If the posts do not have pictures, write the database directly. If the posts have pictures, they need to be stored in the storage provided by cloud development first, get the returned file Id (url of picture) and then write it into the database, core code:

    for (let i = 0; i < img_url.length; i++) {
      var str = img_url[i];
      var obj = str.lastIndexOf("/");
      var fileName = str.substr(obj + 1)
      console.log(fileName)
      wx.cloud.uploadFile({
        cloudPath: 'post_images/' + fileName,//File name must be specified, otherwise the file id returned is incorrect
        filePath: img_url[i], // Temporary File Path for Small Programs
        success: res => {
          // get resource ID: 
          console.log(res)
          //Put the address of the uploaded successful picture into the array
          img_url_ok.push(res.fileID)
          //If all of them are uploaded, the image path can be saved to the database.
          if (img_url_ok.length == img_url.length) {
            console.log(img_url_ok)
            that.publish(img_url_ok)
          }
        },
        fail: err => {
          // handle error
          console.log('fail: ' + err.errMsg)
        }
      })
    }  

Through img_url_ok.length == img_url.length, we confirm that all pictures have been uploaded and returned the corresponding id, and then perform the operation of writing to the database:


  /**
   * The image was uploaded when the publication was executed, and the file Id of the image was written to the database.
   */
  publish: function(img_url_ok) {
    wx.cloud.init()
    wx.cloud.callFunction({
      name: 'publish_post',
      data: {
        openid: app.globalData.openId,// This cloud can actually be obtained directly.
        author_name: app.globalData.userInfo.nickName,
        content: this.data.content,
        image_url: img_url_ok,
        publish_time: "",
        update_time: ""//Now let the server generate these two times by itself
      },
      success: function (res) {
        // Mandatory refresh, this referee is very rude
        var pages = getCurrentPages();             //  Get the page stack
        var prevPage = pages[pages.length - 2];    // Last page
        prevPage.setData({
          update: true
        })
        wx.hideLoading()
        wx.navigateBack({
          delta: 1
        })
      },
      fail: console.error
    })
  },

Through wx.cloud.callFunction, we call a cloud function (specifying the function name by name), and pass the content of the post, image_url and other information (publisher's nickname, id, etc.) to the cloud. Then look at the cloud function:

exports.main = async (event, context) => {
  try {
    return await db.collection('post_collection').add({
      // The data field represents the JSON data to be added
      data: {
        // Publish the applet in
        //author_id: event.openid, don't pass it on by yourself, use sdk's own
        author_id: event.userInfo.openId,
        author_name: event.author_name,
        content: event.content,
        image_url: event.image_url,
        // What is the impact of server time and local time?
        publish_time: new Date(),
        // update_time: event.update_time, // last update time, publish or comment trigger update, currently using server-side time
        update_time: new Date(),
        // Default values, some are not currently developed, so they are not set
        // Comme_count: 0, // comment number, read the database directly, avoid two data representing the same meaning
        watch_count: 3,//Browse Number
        // star_count: 0,//TODO: Number of Collectors
      }
    })
  } catch (e) {
    console.error(e)
  }
}

As you can see, the cloud function writes a database record, and our parameters are brought in through the variable event.

Get a list of Posts

The so-called access to the list of posts is actually to read the database written in the previous section, but we do not need all the information (such as picture url) and require sorting by time. If you are familiar with the database, you will find that this is another query statement.

exports.main = async (event, context) => {
  return {
    postlist: await db.collection('post_collection').field({// Specify the fields to be returned
      _id: true,
      author_name: true,
      content: true,
      title: true,
      watch_count: true
    }).orderBy('update_time', 'desc').get(),//Designated Sorting Basis

  }
}

Browse the content of the post

Browse the content of the post and give the id of a post, which is brought in by clicking on the list of posts:

  onItemClick: function (e) {
    console.log(e.currentTarget.dataset.postid)
    wx.navigateTo({
      url: '../postdetail/postdetail?postid=' + e.currentTarget.dataset.postid,
    })
  },

Then, in the cloud function, you get all the data according to this id:

exports.main = async (event, context) => {
  
  return {
    postdetail: await db.collection('post_collection').where({
      _id: event.postid
    }).get(),
  }
}

After getting all the data, load the picture of the post according to the picture id:

    // Getting content
    wx.cloud.callFunction({
      // Cloud function name 
      name: 'get_post_detail',
      data: {
        postid: options.postid
      },
      success: function (res) {
        var postdetail = res.result.postdetail.data[0];
        that.setData({
          detail: postdetail,
          contentLoaded: true
        })
        that.downloadImages(postdetail.image_url)
      },
      fail: console.error
    })

Here, that. download Images (postdetail. image_url) loads the picture:

  /**
   * Get the fileId of the picture from the database, then go to the cloud storage to download, and finally load it.
   */
  downloadImages: function(image_urls){
    var that = this
    if(image_urls.length == 0){
      return
    } else {
      var urls = []
      for(let i = 0; i < image_urls.length; i++) {
        wx.cloud.downloadFile({
          fileID: image_urls[i],
          success: res => {
            // get temp file path
            console.log(res.tempFilePath)
            urls.push(res.tempFilePath)
            if (urls.length == image_urls.length) {
              console.log(urls)
              that.setData({
                imageUrls: urls,
                imagesLoaded: true
              })
            }
          },
          fail: err => {
            // handle error
          }
        })
      }
    }
  },

Comments

The logic of commenting and posting is similar, but the data written is different, and there is no need to elaborate.

summary

As I said before, cloud development weakens the back end (simplifying authentication is also weakening the back end), so the benefits are to improve development efficiency, because front-end and back-end alignment has always been a time-consuming thing, and the small program itself is the main focus.
It's a small application. There's really no need to introduce too many developers. But cloud development is not omnipotent. For example, when I first wanted to be an RSS reader, the back end needed to aggregate information. At present, cloud development can not do it.

Personally, as long as it is a small information program, such as news and video, cloud development is very weak at present, because the support of database is too simple (or maybe it's my dish, I haven't found a good solution, welcome to pat bricks). But if it is a small program mentioned in this article that users themselves will generate information, then cloud development will have the advantage of development efficiency.

Finally, cloud development currently provides 2G databases and 5G storage. Whether some small programs with large number of users are enough is also a problem. At present, there is no paid version.

In general, the first contact with small program development, or found that there are many worthy of learning.

Source Link

https://github.com/TencentCloudBase/Good-practice-tutorial-recommended

If you want to share your technical stories / experiences in developing CloudBase using the cloud, please leave a message to contact us.

Posted by AndieB on Fri, 23 Aug 2019 00:13:44 -0700