First Assignment--小小烧鱼通讯录--832201126谢荣城

832201126谢荣城 2024-10-31 01:03:44
Assignment 1Front-end and Back-end Separation Contacts Programming
Course for This Assignment2401_MU_SE_FZU
Assignment RequirementsFirst Assignment -- Front-end and Back-end Separation Contacts Programming
NameRongcheng Xie
Objectives of This Assignmentdevelop a contacts mini-program
Other ReferenceWeChat Developer Tools - WeChat Mini Program Design Guide - Javascript Style Guide
complete codeComplete code demo
front-endfront-end code
back-endback-end code

@

Catalog

  • introduction
  • 1. Task Overview: Building a Digital Address Book
  • 1.1 Pogram development
  • Main function development
  • Tools and Environment
  • Design Approach
  • Database Usage and Front-End & Back-End Interaction
  • 1.2 Coding Standard Link
  • 2. PSP Table
  • 3. Product Presentation
  • 3.1 User Interface
  • 3.2 Feature 1: Add
  • 3.3 Feature 2: Modify
  • 3.4 Feature 3: Delete
  • 3.5 Feature 4: search function
  • 3.5 Feature 5: Upload avatar function
  • 4. Design Process
  • 4.1 Front-end Design
  • 4.1.1 Requirement Analysis for the Contacts Mini-Program
  • Functional Requirements
  • Non-Functional Requirements
  • 4.1.2 Interface Design for the Contacts Mini-Program
  • Home Screen (Contact List)
  • Add/Edit Contact Screen
  • Contact Detail Screen
  • Confirmation and Feedback
  • 4.2 Back-End Design for the Contacts Mini-Program (Using Tencent Cloud)
  • 4.2.1 Back-end data management
  • Database Design
  • API Design
  • Data Validation and Security
  • Error Handling and Logging
  • Deployment and Scalability
  • Conclusion

introduction

The core function of the project implements a front-end and back-end separation architecture, which not only makes the development more modular and maintainable, but also provides higher flexibility for function expansion and data processing. In the front end, the small program interface design is simple and clear, focusing on user experience; In the back-end, API is used to realize the function of adding, deleting, checking and changing data, so as to ensure the real-time performance and consistency of data.

1. Task Overview: Building a Digital Address Book

1.1 Pogram development

Main function development

  • Contact List Page: Displays all contacts, allowing users to click and view details. A search function is added for quick contact lookup.
  • Contact Details Page: Shows detailed information for a single contact, with options to edit or delete. The card layout design makes information presentation clearer.
  • Add/Edit Contact Page: Users can add new contacts or update existing information. Validation is implemented to ensure that phone number format and name fields are correctly filled.

    功能图

Tools and Environment

  • WeChat Developer Tools: Used for writing, debugging, and previewing the mini-program; it is the main tool for mini-program development.
  • Languages: Utilizes languages supported by WeChat mini-programs, including WXML (similar to HTML), WXSS (similar to CSS), and JavaScript for page structure, styling, and logic.
  • Package Manager: npm, used for managing dependencies and libraries within the project.

微信开发者工具

Design Approach

  • Simple and Clear Interface: To ensure users can quickly get started, the interface design follows a simple and clean layout, avoiding excessive decorative elements. Each page adheres to a "less is more" principle, allowing users to easily view, add, and edit contacts.
  • Clear Functional Sections: The contacts app is divided into distinct pages for contact list, contact details, and adding contacts, making navigation straightforward.

Database Usage and Front-End & Back-End Interaction

  • Database Usage: The database stores contact information like name, phone number, and address. Each operation (such as adding, editing, or deleting a contact) directly updates the database to maintain data consistency and real-time accuracy. A lightweight cloud database is chosen for quick access and flexible data management.
  • Front-End & Back-End Interaction: The mini-program’s front end communicates with the back end through API requests. For example, when the front end requests the contact list, the back end retrieves the data from the database and returns it. Similarly, when a user adds, modifies, or deletes a contact, the front end calls the corresponding API, which the back end processes to update the database. This interaction ensures smooth data flow between front and back ends, improving system maintainability and scalability.

前后端交互流程图

2. PSP Table

Personal Software Process StagesEstimated Time (minutes)Actual Time (minutes)
Planning150120
• Estimate150120
Development1050880
• Analysis150120
• Design Spec12090
• Design Review6050
• Coding Standard4030
• Design120100
• Coding300250
• Code Review5040
• Test6080
Reporting300200
• Test Report8050
• Size Measurement6040
• Postmortem & Process Improvement Plan160110
Total15001200

3. Product Presentation

3.1 User Interface

Wechat mini program entrance, click "小小烧鱼通讯录“” to enter
![mini program](https://i-blog.csdnimg.cn/direct/c9a69c2edff44159a43abe5f0b06d011.png#pic_center =330x680)
You will see the following user interface:
![用户界面](https://i-blog.csdnimg.cn/direct/e7fc4f4f80eb426d853e9cddaed0bb67.gif#pic_center =330x680)

3.2 Feature 1: Add

Click the blue "Add User" button in the top-right corner to enter the user addition interface.
![添加按钮](https://i-blog.csdnimg.cn/direct/abbed724a9ef4af8a4e4bc6d6ccfcffa.png#pic_center =330x680)
The mini program will allow adding new contact information, and we can input and save the contact information to the user interface:
![添加联系人](https://i-blog.csdnimg.cn/direct/e6b0045690c2439aacda3c896884edbb.gif#pic_center =330x680)
After adding the operation, the data in the Mini Program Cloud Development Console:

数据库展示


If the contact is added without the two most important information, name or mobile phone number, it will be prompted to fill in the necessary information:
![填写必要信息](https://i-blog.csdnimg.cn/direct/f2a40495cd5c4214a19006048fa46532.gif#pic_center =330x680)

3.3 Feature 2: Modify

Click the Edit Contact button at the bottom of the screen:
![修改联系人](https://i-blog.csdnimg.cn/direct/9bbb5300e80d47a7aeb0e98d2e7d7dc6.png#pic_center =330x680)
The mini program will allow modifying contact information:
![修改步骤](https://i-blog.csdnimg.cn/direct/1f9a79fd7b2a4304a58a87142216cf70.gif#pic_center =330x680)
After modifying the operation, the data in the Mini Program Cloud Development Console:

数据库变化

3.4 Feature 3: Delete

Click the Delete Contact button at the bottom of the screen:
![删除按钮](https://i-blog.csdnimg.cn/direct/893ea05c60f241fd82c90adaee379290.png#pic_center =330x680)

The mini program will allow deleting contact information:
![删除顺序](https://i-blog.csdnimg.cn/direct/ff2198412f994a0ea6f14a9dd68ab6c3.gif#pic_center =330x680)

After deleting the operation, the data in the Mini Program Cloud Development Console:

数据库

3.5 Feature 4: search function

Can search for contacts based on key letters entered
![搜索功能](https://i-blog.csdnimg.cn/direct/7ba122b972574c28aa60bf2a4c329c26.gif#pic_center =330x680)

3.5 Feature 5: Upload avatar function

After clicking Upload the avatar, you can choose to take a photo or choose from an album:
![头像选择](https://i-blog.csdnimg.cn/direct/8ffb91311f78478eb80098233a0bf2db.gif#pic_center =330x680)

4. Design Process

4.1 Front-end Design

4.1.1 Requirement Analysis for the Contacts Mini-Program

Functional Requirements

  • View Contacts: Display a list of all saved contacts, allowing users to easily browse through their contacts.
  • Add Contact: Enable users to input new contact information (e.g., name, phone number) and save it to the database.
  • Edit Contact: Allow users to select a contact, edit details, and update the information in the database.
  • Delete Contact: Provide an option for users to delete unwanted contacts, which removes the data from the database.
  • Search Contact: Implement a search function to help users quickly find specific contacts by name or other details.

    Non-Functional Requirements

  • Usability: The interface should be intuitive and simple, allowing users to easily navigate and manage contacts.
  • Performance: Ensure fast response times for loading, adding, editing, and deleting contacts.
  • Data Consistency: Maintain data accuracy and consistency between the front-end and back-end, especially during add, edit, and delete operations.
  • Security: Secure data transmission between the front-end and back-end, protecting contact information.
  • Compatibility: The program should be compatible with the latest versions of the WeChat Mini Program environment.

4.1.2 Interface Design for the Contacts Mini-Program

Home Screen (Contact List)

  • Layout: A simple list view displaying all contacts with basic details like name and phone number.
  • Features:
    • Search Bar: Positioned at the top for quick searching.
    • Add Contact Button: Visible top-right corner, enabling easy access to add new contacts.
  • User Interaction: Tapping on a contact navigates to the contact’s detailed view.

Add/Edit Contact Screen

  • Layout: Input fields for contact details such as name, phone number, and optional fields (email, address).
  • Features:
    • Save Button: Positioned at the bottom to confirm changes.
    • Validation: Ensures required fields (e.g., name and phone number) are filled correctly.
  • User Interaction: User inputs data and saves, triggering data to be sent to the backend.

Contact Detail Screen

  • Layout: Displays full contact details in a card layout for easy reading.
  • Features:
    • Edit and Delete Buttons: Allows quick access to modify or remove the contact.
  • User Interaction: Users can tap "Edit" to modify details or "Delete" to remove the contact, with a confirmation prompt for deletion.

    Confirmation and Feedback

  • Layout: Pop-up dialogs for actions like delete confirmation and feedback messages on save.
  • Features:
    • Confirmation Prompts: Displayed for actions that alter data (e.g., delete).
    • Feedback Messages: Success or error messages shown briefly after actions.

Here's some important code:

<!-- index界面 -->
<!-- navi -->
<view class="navi">
  <view class="navitext">
    <text class="scrolling-text">小小烧鱼</text>
    <text class="static-text">通讯录</text>
  </view>
  <view class="add-circle" bindtap="onAddContact">
    <text class="add-text">+</text>
  </view>
</view>

<!-- 搜索框独立图层 -->
<view class="search-container">
  <input class="search-input" placeholder="搜索联系人" bindinput="onSearchInput" />
</view>

<!-- contact -->
<scroll-view class="contact" 
    scroll-y="true" 
    scroll-into-view="{{loc}}" 
    style="height: {{screenHeight}}rpx; position: relative; left: 0rpx; top: 427rpx" 
    scroll-with-animation="true">
  <block wx:for="{{filteredContacts}}" wx:key="letter">
    <view class="group" wx:if="{{item.group.length != 0}}" id="{{item.letter}}">
      <view class="header">{{item.letter}}</view>
      <navigator class="card" 
          wx:for="{{item.group}}" 
          wx:for-item="star" 
          wx:key="*this" 
          url="/pages/card/card?id={{star._id}}">
        <view class="name">{{star.name}}</view>
      </navigator>
      <view class="line"></view>
    </view>
    <view wx:else id="{{item.letter}}"></view>
  </block>
</scroll-view>

<!-- 右侧字母栏 -->
<view class="shortcut">
  <view class="letter" wx:for="{{letters}}" wx:key="*this" bindtap="onTapScroll" data-loc="{{item}}">
    {{item}}
  </view>
</view>

  <!-- card界面展示 -->
<view class="contact-detail">
  <!-- 圆形头像区域 -->
  <view class="avatar-section" bindtap="onSelectPhoto">
    <image class="avatar" src="{{contact.avatar || '/img/default-avatar.png'}}" mode="aspectFill" />
    <text class="select-text" wx:if="{{!contact.avatar}}">选择头像</text>
  </view>

  <!-- 联系人基本信息 -->
  <view class="info-section">
    <view class="field editable">
      <view class="label">姓名:</view>
      <input class="value" value="{{contact.name}}" disabled="{{!isEditing}}" bindinput="onNameInput" />
    </view>

    <view class="field editable">
      <view class="label">电话:</view>
      <input class="value" value="{{contact.phone}}" disabled="{{!isEditing}}" bindinput="onPhoneInput" />
    </view>

    <view class="field editable">
      <view class="label">邮箱:</view>
      <input class="value" value="{{contact.email}}" disabled="{{!isEditing}}" bindinput="onEmailInput" />
    </view>

    <view class="field editable">
      <view class="label">地址:</view>
      <input class="value" value="{{contact.address}}" disabled="{{!isEditing}}" bindinput="onAddressInput" />
    </view>

    <view class="field editable">
      <view class="label">备注:</view>
      <textarea class="value" value="{{contact.note}}" disabled="{{!isEditing}}" bindinput="onNoteInput" />
    </view>
  </view>

  <!-- 操作按钮 -->
  <view class="operation-section">
    <button type="primary" bindtap="onEditContact" wx:if="{{!isEditing}}">修改联系人</button>
    <button type="primary" bindtap="onSaveContact" wx:if="{{isEditing}}">保存联系人</button>
    <button type="warn" bindtap="onDeleteContact">删除联系人</button>
  </view>
</view>

4.2 Back-End Design for the Contacts Mini-Program (Using Tencent Cloud)

4.2.1 Back-end data management

Database Design

  • NoSQL Database: Uses Tencent Cloud’s NoSQL database in WeChat Cloud Development for storing contact data.
  • Collection Structure: The contacts collection holds documents for each contact, with fields like _id, _openid (user ID), address, avatar, email, name, note, and phone.

API Design

  • Cloud Functions: CRUD operations are managed with cloud functions.
    • Create Contact: Adds a contact document.
    • Read Contacts: Retrieves contacts.
    • Update Contact: Updates contact data by _id.
    • Delete Contact: Deletes contact by _id.

Data Validation and Security

  • Data Validation: Checks required fields (name, phone) before saving.
  • Security: Limits access to user-specific data with _openid.

Error Handling and Logging

  • Error Responses: Returns errors for invalid requests.
  • Logging: Logs operations for debugging and tracking.

Deployment and Scalability

  • Tencent Cloud Hosting: Uses Tencent Cloud for scalable, secure hosting.
  • Scalability: Designed to support more contacts and users.

Here's some important code:

  <!-- index.js操作展示 -->
wx.cloud.init({
  env: 'george-8gktege9596a5ba5' 
});

const db = wx.cloud.database();  
const contactsCollection = db.collection('contacts');  

Page({
  data: {
    letters: "ABCDEFGHIJKLMNOPQRSTUVWXYZ#",  
    contact: [],  
    filteredContacts: [],  
    loc: "",
    screenHeight: 0,
    searchTerm: ""  
  },

  loadContactsFromDatabase() {
    let self = this;
    contactsCollection.field({
      name: true,  
      _id: true    
    }).get({
      success: res => {
        let contacts = res.data;  
        self.arrangeContact(contacts);  
      },
      fail: err => {
        console.error('从数据库获取联系人失败:', err);
      }
    });
  },

  arrangeContact(contacts) {
    var self = this;
    var contact = [];

    for (var i = 0; i < self.data.letters.length; i++) {
      var letter = self.data.letters[i];
      var group = [];

      for (var j = 0; j < contacts.length; j++) {
        let contactItem = contacts[j];
        let contactName = contactItem.name;
        let contactLetter = /^[\u4e00-\u9fa5]+$/.test(contactName[0]) 
          ? "#"  
          : contactName[0].toUpperCase();  

        if (contactLetter === letter) {
          group.push(contactItem);  
        }
      }

      contact.push({
        letter: letter,
        group: group
      });
    }

    self.setData({
      contact: contact,
      filteredContacts: contact  
    });
  },

  onSearchInput: function (e) {
    const searchTerm = e.detail.value.toLowerCase();  
    this.setData({
      searchTerm: searchTerm
    });

    this.filterContacts();
  },

  filterContacts: function () {
    const self = this;
    const searchTerm = self.data.searchTerm;

    if (!searchTerm) {
      self.setData({
        filteredContacts: self.data.contact
      });
      return;
    }

    const filteredContacts = self.data.contact.map(group => {
      const filteredGroup = group.group.filter(contact =>
        contact.name.toLowerCase().includes(searchTerm)
      );
      return {
        letter: group.letter,
        group: filteredGroup
      };
    }).filter(group => group.group.length > 0);  

    self.setData({
      filteredContacts: filteredContacts
    });
  },

  onLoad: function () {
    this.loadContactsFromDatabase(); 
    var screenHeight = wx.getSystemInfoSync().screenHeight;
    this.setData({
      screenHeight: screenHeight * 2,
    });
  },

  onTapScroll: function (e) {
    var loc = e.currentTarget.dataset.loc;  
    this.setData({
      loc: loc  
    });
  },

  onAddContact() {
    wx.navigateTo({
      url: '/pages/addContact/addContact'  
    });
  }
});
  <!-- card.js操作展示 -->
wx.cloud.init({
  env: 'george-8gktege9596a5ba5'  
});

const db = wx.cloud.database();  
const contactsCollection = db.collection('contacts');  

Page({
  data: {
    contact: {},  
    contactId: "",  
    isEditing: false  
  },

  onLoad: function (options) {
    const self = this;

    const contactId = options.id;
    self.setData({ contactId: contactId });

    contactsCollection.doc(contactId).get({
      success: function (res) {
        console.log("数据库返回的数据:", res.data); 

        self.setData({
          contact: res.data  
        });
      },
      fail: function (err) {
        console.error("数据库读取失败: ", err);
        wx.showToast({
          title: '获取联系人失败',
          icon: 'none'
        });
      }
    });
  },
onSelectPhoto: function () {
  wx.chooseImage({
    count: 1,
    success: res => {
      const tempFilePath = res.tempFilePaths[0];
      this.uploadImage(tempFilePath, 'avatar');
    }
  });
},

uploadImage: function (tempFilePath, type) {
  const cloudPath = `${type}s/${Date.now()}-${Math.floor(Math.random() * 1000)}.png`;
  wx.cloud.uploadFile({
    cloudPath,
    filePath: tempFilePath,
    success: res => {
      const fileID = res.fileID;
      this.updateContactAvatar(fileID);
    }
  });
},

updateContactAvatar: function (fileID) {
  contactsCollection.doc(this.data.contactId).update({
    data: {
      avatar: fileID  
    },
    success: () => {
      this.setData({
        'contact.avatar': fileID  
      });
      wx.showToast({
        title: '头像已更新',
        icon: 'success'
      });
    }
  });
},

  onEditContact: function () {
    this.setData({
      isEditing: true  
    });
  },

  onNameInput: function (e) {
    this.setData({
      'contact.name': e.detail.value
    });
  },

  onPhoneInput: function (e) {
    this.setData({
      'contact.phone': e.detail.value
    });
  },

  onEmailInput: function (e) {
    this.setData({
      'contact.email': e.detail.value
    });
  },

  onAddressInput: function (e) {
    this.setData({
      'contact.address': e.detail.value
    });
  },

  onSaveContact: function () {
    const self = this;
    const updatedContact = self.data.contact;

    contactsCollection.doc(self.data.contactId).update({
      data: {
        name: updatedContact.name,
        phone: updatedContact.phone,
        email: updatedContact.email,
        address: updatedContact.address
      },
      success: function () {
        wx.showToast({
          title: '联系人已更新',
          icon: 'success'
        });

        self.setData({
          isEditing: false
        });
      },
      fail: function (err) {
        wx.showToast({
          title: '更新失败',
          icon: 'none'
        });
        console.error("更新联系人失败: ", err);
      }
    });
  },

  onDeleteContact: function () {
    const self = this;
    wx.showModal({
      title: '删除确认',
      content: '你确定要删除这个联系人吗?',
      success: function (res) {
        if (res.confirm) {
          contactsCollection.doc(self.data.contactId).remove({
            success: function () {
              wx.showToast({
                title: '联系人已删除',
                icon: 'success'
              });

              wx.redirectTo({
                url: '/pages/index/index',  
              });
            },
            fail: function (err) {
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              });
              console.error("删除联系人失败: ", err);
            }
          });
        }
      }
    });
  }
});

Conclusion

The development of this contacts mini-program provided valuable experience in designing and implementing a front-end and back-end separated architecture. Leveraging Tencent Cloud's NoSQL database and cloud functions, the back-end ensures secure, scalable, and efficient data management. The front-end, designed for ease of use, offers users intuitive access to contact management features, including adding, editing, and deleting contacts. This project not only reinforces technical skills in WeChat mini-program development but also highlights the importance of modularity, security, and data integrity in application design.

...全文
91 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
雀食牛逼

170

社区成员

发帖
与我相关
我的任务
社区描述
2401_MU_SE_FZU
软件工程 高校
社区管理员
  • FZU_SE_TeacherL
  • 助教-吴可仪
  • 助教-孔志豪
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧