preface

Recently I am doing a small program, is based on small program cloud development, when doing small program projects using cloud development is really convenient is a lot. I will also talk about the cloud development behind, after all, this project is the use of cloud development, cloud development content partners in need can also go to see the official documents, cloud development documents. The development of the project has been going on for some time. Although only part of the functions have been realized, I still can’t help writing an article to share the results and problems encountered in the project during this period of time, and I will gradually improve the project later. Project source on Github, if you feel good friends can give a star, imitation headlines project address.

The project,

The following will introduce the detailed project, although the use of cloud development saves a lot of time but before and after the things you need to do to work a bit big, in this short period of time I didn’t finish the whole project, just realized the home page, page for details, and main functions such as login page The first thing I will need to get the data interface design good database to prepare for the data acquisition, The MongoDB database developed by the small program cloud is used to store data in the cloud database and operate the database using cloud functions

News homepages


The home page interface

The input box is bound to a tap event that changes the placeholder value when the input box is clicked but no value is entered. There is a button on the right side of the TAB bar. Clicking the button will bring up a pop-up layer, which is shown in the GIF in the front. It is the selection box of news type. “I think it’s a great way to do that,” he said. “I think it’s a great way to do that.” 6 tabs are set in the TAB bar, but only 4 tabs will be displayed. You can drag the TAB bar left and right to display the others, and set the recommended page to be activated by default. Because each each TAB page code is basically the same, just in the first column is placed at the top information page recommendation yes, there is access to data, the data acquisition in the following code will be fine, in order to improve the reuse of code, using the template here, to reuse the code written in the book written in another file, when using direct call. Every label corresponding creates a collection, I created a collection of the top news is another, and to each of the information to design good field is convenient to get data and use the data, because the cloud database can be json or CSV file to import, and on every news also needs to pull load data need more data, It takes time and trouble to build data by myself, so I wrote a crawler here to crawl the data I need and save it in JSON file, and directly import the data into the database. This design also makes it easier to get data from the database. Write a module function to get the data for each tag. The fields of each piece of data are as follows, in which news_id plays an important role in connecting each piece of news on the home page with the corresponding detail page.

Specific function realization

In each TAB to use the template, and set up a data (incoming need to display the corresponding to different page news information, used to display on the page), because the default page activation page is recommended in the onload event is triggered when the default page loading recommended data, at the same time sets the recommendation page to page has been activated, wrote a load function data loading here

 module: function(title) {
      let counter = this.data.counter
      // console.log(title)
      wx.cloud.callFunction({
        name: 'module',
        data: {
          counter: counter,
          title: title
        }
      }).then(res => {
        // console.log(res)
        let cnews = this.data.cnews
        let data = res.result.data
        // console.log(data)
        for(let i = 0; i < data.length; i++) {
          // console.log(data[i].date)
          data[i].date = data[i].date.slice(0, 10)
          cnews.push(data[i])
          this.imgCheck(data[i].images, data.new_id, title)
        }
        // console.log(data)
        this.setData({
          hiddenLoading: true,
          cnews: cnews,
          counter: counter+1
        })
      })
    }
Copy the code

Passing in a title is the title of the tag that is currently displayed, the default is recommendation, a counter count is used, and only 5 news items are loaded at a time. Fetching news information from the database is handled by a cloud function

#### Obtain data from cloud functions// cloud function entry file const cloud = require('wx-server-sdk'Cloud.init () const db = cloud.database() // exports.main = async (event, context) => {cloud.init() const db = cloud.database() // exports.main = async (event, context) => {return await db.collection(event.title).skip((event.counter-1)*5).limit(5).get()
}
Copy the code

Two data are passed to the cloud function, one is title, which is to obtain information from the corresponding collection, and the other is counter, which is used to calculate the location of obtaining information. Because data needs to be loaded when more news is pulled up and loaded, I set 5 data to be loaded each time, so I pass a counter to the cloud function. Every time the cloud function is called to get the data counter from the database once, it will +1, so that every time the data is loaded, it will ignore the loaded data and load the data from behind. The array that holds the data is updated each time the data is loaded, and the index.wxml page on the home page will judge and fetch the data and display it to the corresponding TAB using a for loop

The drop-down refresh

In the top news section, the data retrieval is actually not very special, I’m just pulling the most recent news from the top news collection from the cloud database, and then I’m showing the page and there’s also a drop-down refresh, using the onPullDownRefresh function of the applet to pull down the refresh to get the latest data, In addition, the latest data interpolation is displayed at the top, which is not obvious because the data needs to be inserted to the front of the collection each time

  onPullDownRefresh: functionWx. showToast({title: {title: {title: {title: {title: {title: {title: {title: {title: {title: {title: {title: {title: {title: {title: {title: {title:'Recommended',
        image: '.. /.. /.. / image/loading. PNG '
      })
      let title = this.data.title;
      wx.cloud.callFunction({
        name: 'module',
        data: {
          counter: 1,
          title: title
        }
      }).then(res => {
        // console.log(res)
        let cnews = this.data.cnews
        let datas = res.result.data
        let data = datas.concat(cnews)
        this.setData({
          hiddenLoading: true,
          cnews: data,
        })
      })
    }
Copy the code

Photo identification

In the module function, I used an image yellow authentication function and an image recognition interface of Tencent. After all, not all pictures can be displayed, so I wrote a imgCheck function to detect all pictures of each news, and delete the news if the pictures are not qualified. I did not use pictures to test, more impossible to show it, I believe we all understand (wretched laugh). An onchange event is generated when different tabs are switched, and the onchange event gets the title and index. In the onchange event, the module function is used to obtain the data of the corresponding title and determine whether this data is recently loaded. If it is the function loaded by the last onchange event, the data saved by the last event will be displayed. WXML also determines whether the page was activated last time to display the corresponding data. The front has been talking about the back end of things, I also this article is to talk about the cloud, to tell the truth, cloud development is really convenient a lot, a person can fix the front and back end of things. But just to make it easier for you to understand, let me tell you a little bit about the interface. Now that we’ve got the data, the last thing we need to do is present the data, every single piece of data

<van-tab title="Recommended"> <! Each news box can be clicked into the details page --> <van-panel class="topping" title="{{topTitle}}" status="Top" use-footer-slot bind:tap="showTopDetail" data-item="{{topNew_id}}">
        <view class="images">
            <image src="{{images[0]}}" />
            <image src="{{images[1]}}" />
            <image src="{{images[2]}}" />
          </view>
          <view solt="footer" class="footer">
            <view class="author">{{topAuthor}}</view>
            <view class="comment"> {{topComment}}</view> <view class="Date">{{topDate}}</view>
          </view>
      </van-panel>

      <template is="container" data="{{news: active1 == 'news'? news:cnews, hiddenLoading}}"></template>
    </van-tab>
Copy the code
<template name="container">
    <view class="container">
        <loading hidden="{{hiddenLoading}}"></loading>
        <view class="news" wx:for="{{news}}" wx:for-item="info" wx:key="info.new_id">
            <van-panel class="new" title="{{info.title}}" bind:tap="showDetail" use-footer-slot data-item="{{info.new_id}}">
                <view class="images" wx:if="{{info.images.length > 0}}">
                    <image src="{{info.images[0]}}"/>
                    <image src="{{info.images[1]}}"/>
                    <image src="{{info.images[2]}}"/>
                </view>
                <view solt="footer" class="footer">
                    <view class="author">{{info.author}}</view>
                    <view class="comment"> comments {{info.comments}}</view> <view class="Date">{{info.date}}</view>
                </view>
            </van-panel>
        </view>
    </view>
</template>
Copy the code

This is the MVVM idea, binding the data to the UI interface, retrieving the data from the JS file, and then using it. Here, the number of pictures per news is uncertain, and only three pictures are displayed at most. So we fixed the three image tags and fixed the size of the image, so that the image will not be displayed when there is no image.

Details page

A lot of things in the home page I said in detail page is no longer said, we do not understand can go to see the source code, after all, speak so much nonsense is a waste of time, I try to pick out the most wonderful part to write.

Home page to details page

Every news on the home page is bound with a jump tap event. After clicking the news, it will jump to the details page, and the ID and title of the news will be passed to the details page as parameters.

  showDetail: function(e) {// Click article to display article detailslet item = e.currentTarget.dataset.item;
      lettitle = this.data.title; // console.log(e) wx.navigateTo({ url:`.. /detail/detail? contentId=${item}&title=${title}`})}Copy the code

interface

After clicking to jump to the details page, the corresponding news ID will be obtained in the event of onload, and the ID will be stored in data. Since I didn’t climb down when I climbed the details page, I randomly put some simple content inside the content.

For details page, I have divided the page into content section and comments. Then, a fixed button is used to fix the input box and other buttons at the bottom of the screen. The content part is divided into four parts, namely the title part, the author’s head picture and nickname, the content part, the likes and forwarding part, and the data in the database is displayed on the interface.

In the second part I used a Flex floating layout for displaying images and nicknames and set flex to 1 for the nickname section so that the avatar and the focus button are on either side. The avatar uses an image tag and the size of the image tag is fixed, because the image uploaded by the user must be of different sizes. Part four is just a matter of putting images and content in with 4 Views and using a Flex layout.

Specific function implementation

Now that the interface layout is done, it is time to get the data. When you click on the news to enter the details page, you will get the ID and title of the news. In this way, you can get the corresponding news data from the cloud database by the unique ID (the ID of each doc) and title (the name of the collection). Here the code will not be posted, with the front page of the same, there is a need to go to Github to see the source code.

Now, the comments section, which I think is kind of interesting and there are permissions to update the database, which I didn’t talk about before but I’m going to put it in the comments section. Fixed a comment box at the bottom of the page, including input box, jump to comment button, favorites button, forward button.





submit: function() {// Implement the comment function to synchronize published comments to the cloud databaselet value = this.data.inputValue;
    let new_id = this.data.new_id;
    let userInfo = this.data.userInfo
    // let new_id = '6594157273642172936'
    if(userInfo){
      comments.where({
        new_id: new_id
      }).get({
        success: (res) => {
          // console.log(res)
          let comms= res.data[0].comments;
          let people = {
            content: value,
            like: 0,
            avatar: userInfo.avatarUrl,
            nickname: userInfo.nickname
          }
          comms.unshift(people);
          // console.log(comm)
          this.setData({
            comms: comms,
            input: ' ',
          })
          wx.cloud.callFunction({
            name: 'updateComments',
            data: {
              new_id: new_id,
              comms: comms
            }
          }).then(res =>{
            console.log(res)
          })
  
        }
      })
    }
  }
Copy the code

In the comments section of the database, I just created a set of comments, starting with the news new_id. Each comment has a new_id, and each comment of the news is set as an object. After all, comments also include avatar nicknames, likes, comment content, etc. The advantage of setting up a comment database like this is that as long as you get the news ID in a collection, you can get the comments corresponding to the news.

Start I didn’t use the cloud when updating the database function, but direct updating data in js, request return information display is success but the update number is 0, but when I found the data in the database view is not updated, checked the documents found that is a question of authority, because the data change only management or the founders of the data, And the data is manually input into the cloud database by myself. When the database is directly updated in JS, it is not the creator and there is no administrator authority in the small program side, so there is no authority to modify the data. Since it can’t be the creator who wants to modify the data, it has to be the administrator, so HERE I use cloud functions to modify the data. Here we should be aware of the cloud function permissions is what level, here to give you a look at the official documentation.








addLike: function(e) {// Click the "like" icon to increase the number of likes and save it to the databaselet item = e.currentTarget.dataset.item;
    let new_id = this.data.new_id;
    let comms = this.data.comms;
    let likeItem = this.data.likeItem;
    let likebool = 'likeItem['+item+'].bool'
    let liken = 'likeItem['+item+'].n'
    if(typeof(likeItem[item]) == "undefined"){
      this.setData({
        [likebool]: false,
        [liken]: 0,
      })
    }

    if(likeItem[item]){
      likeItem[item].n += 1;
      if(likeItem[item].n%2){
        comms[item].like += 1;
      }else{ comms[item].like -= 1; } likeItem[item].bool = ! (likeItem[item].bool); }else{
      likeItem[item].bool = true;
      likeItem[item].n = 0;
      comms[item].like += 1;
    }

    this.setData({
      comms: comms,
      likeItem: likeItem
    })
    // console.log(comms)
    wx.cloud.callFunction({
      name: 'updateComments',
      data: {
        new_id: new_id,
        comms: comms
      }
    }).then(res =>{
      // console.log(res)
    })
  },
Copy the code

On the bottom of the comment input box is a check box button, a picture button, etc. Here I used flex layout to make it easy. This enabled me to insert a comment image and save the image to the cloud. Comment inserts need to be optimized, and I will continue to do so after I write the article. This is a file upload interface wx.cloud.uploadFile developed by the small program cloud. After uploading the picture, a fileID will be generated. I will save the fileID (that is, the image address) to the image of the current comment object and update the local data at the same time. An if is used to determine if the current comment contains an image, and if so, the image will be displayed in the comment. Here I will not post the code, there is a need to see the source code.

conclusion

Because the project is a little big, I only realized part of the functions in a short time, and I will realize other functions in the following time. In fact, writing this project is also for practical cloud development, and I also experienced the benefits of cloud development. There are some deficiencies in the project welcome to point out, have any good suggestions can also contact me. We learn from each other