EE308FZ_First Assignment_Front-end and Back-end Separation Contacts Programming

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
NameMolan Xue
Student IDMU: 22125281 FZU:832201130
Objectives of This AssignmentUsing web frameworks or other platforms to implement a front-end and back-end separated contacts management system with basic functionalities like adding, modifying, and deleting contacts.
Other Reference1. WeChat Mini Program Design Guide 2. Javascript Style Guide 3. WeChat Developer Tools 4. The Art of Construction

1. Task Overview: Building a Digital Address Book

1.1 Task Description

Developing a Separated Address Book System
The first assignment focuses on creating a contact management system that emphasizes the separation of front-end and back-end functionalities. This assignment includes three core functions:

  1. Adding Contacts: Implement a feature that allows users to add contact information such as names and phone numbers. This data must be securely stored in a back-end database.
  2. Modifying Contacts: Ensure that contact information can be modified by retrieving data directly from the back-end database, with caching strictly prohibited.
  3. Deleting Contacts: Facilitate the deletion of contact information, requiring the operation to be executed directly through the back-end database.

After successfully implementing these basic functions, the project must be deployed to a cloud server, ensuring accessibility and usability.

1.2 Github Repository Link

1.3 Coding Standard Link

2. PSP Table

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning180240
• Estimate180240
Development12601680
• Analysis180240
• Design Spec180240
• Design Review90120
• Coding Standard6080
• Design180240
• Coding480720
• Code Review6080
• Test3040
Reporting360480
• Test Repor90120
• Size Measurement6080
• Postmortem & Process Improvement Plan210280
Sum18002400

3. Product Presentation

3.1 User Interface

Firstly, find SoCiaLConTacT in my Recently Used Mini Programs section and click to enter.
Operation Process
You will see the following user interface:
User Interface
Currently, the data for the Mini Program Cloud Development Console is as follows:
Mini Program Cloud Development Console

3.2 Feature 1: Add

Click the Add New Contact button at the bottom of the screen:
Adding
The mini program will allow adding new contact information, and we can input and save the contact information to the user interface:
gif1
After adding the operation, the data in the Mini Program Cloud Development Console:
After adding

3.3 Feature 2: Modify

Click the Edit Contact button at the bottom of the screen:
Modifying
The mini program will allow modifying contact information:
gif2

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

3.4 Feature 3: Delete

Click the Delete Contact button at the bottom of the screen:
Deleting
The mini program will allow deleting contact information:
gif3

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

3.5 Feature 4: Upload Profile Picture

The mini program will allow uploading local photos to complete contact information:
gif4

4. Design Process

4.1 Functional Structure Diagram

Structure

4.2 Frontend Design

4.2.1 Requirement Analysis

The core functions of the mini program include:

  1. Display contact list, supporting grouping by letters.
  2. Provide a search function that allows real-time searching based on contact names.
  3. Add, edit, delete contacts and upload profile picture.
  4. Display detailed information of contacts, including profile picture, name, birthday, phone number, email, and address.

4.2.2 Interface Design

Design the interface of the mini program according to the requirements. The main interface includes:

  1. Home page (index. wxml): Contact list, alphabetical index, search box, add contact button.
  2. Contact Details Page (card. wxml): Display and edit the detailed information of individual contacts.
  3. Log page (logs. wxml): Display startup logs (optional feature).
Design Steps
Layout DesignUse (scroll view) to display the contact list and support scrolling.
Use the (navigator) component to link to the contact details page.
Design a floating letter index for quick and easy navigation.
Style DesignUse wxss files to define the overall color tone and layout style, such as setting margins, font size, background color, etc., to make the interface more beautiful and user-friendly.

4.2.3 Component Design

  1. Contact list component: responsible for displaying grouped contacts.
  2. Search component: Real time retrieval of user input and dynamic filtering of contact lists.
  3. Contact card component: used to display the basic information and operation buttons (add, modify, delete) of each contact.

4.2.4 Data Processing

  1. Use wx. cloud. database() to retrieve contact data from the cloud.
  2. Group contact data alphabetically and classify Chinese and English names.

4.2.5 Interaction Design

  1. Search Function: Monitor input events in the search box and filter contacts in real-time based on input content.
  2. Jump Function: Click on the contact name to jump to the contact details page, and pass the unique ID of the contact through the URL.

4.3 Backend Design

4.3.1 Cloud Development Environment Settings

  1. Choose a cloud development platform: Use WeChat Cloud for development, providing services such as cloud databases and cloud functions.
  2. Initialize cloud environment: In the entry file (index. js) of the mini program, use wx. cloud. init() to initialize the cloud development environment, specifying the cloud environment ID as mol-3gpukkfsaab8e2e7.

4.3.2 Database Structure Design

Determine the Data Model
Design a contacts collection to store contact information. Each contact document should include the following fields:
_Id: Unique identifier of the contact (automatically generated).
Name: The name (string) of the contact person.
Phone: Contact's phone number (string).
Email: Contact's email address (string, optional).
Address: Contact's address (string, optional).
Create a Cloud Database CollectionCreate a collection named contacts in the WeChat Cloud Development Console to ensure that the data model matches the design.

4.3.3 Design of Data Access Interface

AddingUse the cloud function addContact to handle requests to add new contacts.
In cloud functions, receive contact information from the client and call the contacts. add() method to add a new contact to the database.
ModifyingUse the cloud function updateContact to handle requests to update contacts.
Receive the id and new information of the contact to be updated, find the corresponding document in the database and update it.
DeletingUse the cloud function deleteContact to handle requests to delete contacts.
Receive the id of the contact to be deleted and delete the corresponding document from the database.

4.3.4 Interface Security Design

Permission Control:

  1. Ensure that only authenticated users can access data through user authentication in WeChat mini programs.
  2. Add logic to cloud functions to verify user login status and permissions.

4.3.5 Cloud Function Deployment and Testing

Deploying Cloud Functions: Deploy all designed cloud functions in the WeChat Cloud Development Console.
Functional testing:

  1. Use WeChat developer tools for interface testing to ensure that each cloud function can handle requests correctly and return expected results.
  2. Verify whether the operations of adding, deleting, modifying, and querying data are normal, and ensure that database operations comply with design requirements.

5. Implementation Process

5.1 Frontend Implementation

5.1.1 Homepage Implementation

  1. View layout:
  • Create homepage layout: Design the contact list structure in index.wxml and use thecomponent to wrap the contact list to support scrolling viewing.
<scroll-view class="contact" scroll-y="true" style="height:{{screenHeight}}rpx">
  <view class="search"></view>
  <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>
  </block>
</scroll-view>
  1. Search function:
  • Implement search box: Add a search input box in index.wxml to listen for user input.
<input type="text" bindinput="onSearchInput" placeholder="Search for a contact" />
  • Implement real-time filtering: Implement the onSearchInput method in index.js to retrieve input content and call the filterContacts method for filtering.
  1. Data loading:
  • Load contacts from cloud database: In the loadContactsFromDatabase method, use the cloud database API to retrieve contact data.
contactsCollection.get({
  success: res => {
    this.arrangeContact(res.data);
  },
  fail: err => {
    console.error('Failed to Retrieve Contacts:', err);
  }
});
  1. Data Processing and Grouping:
  • Organize contact data: In the arrangeContact method, group contacts based on letters and process Chinese and English names.
if (/^[\u4e00-\u9fa5]+$/.test(contactName[0])) {
  group.push(contactItem);
}

5.1.2 Implementation of Contact Details Page

  1. View Layout: Design and display detailed information of the contact in card-wxml, including name, phone number, email, etc.
<view class="contact-detail">
  <text>Name:{{contact.name}}</text>
  <text>Phone:{{contact.phone}}</text>
  <!-- Other Information -->
</view>
  1. Data binding: In card.exe, use the passed ID to retrieve detailed information of the specific contact from the cloud database.
const id = this.options.id;
contactsCollection.doc(id).get({
  success: res => {
    this.setData({ contact: res.data });
  }
});

5.1.3 Implementation of Add Contact Function

  1. View layout: Create an add contact page: Design an input form in addContact-wxml where users can enter information such as name, phone number, etc.
  2. Data submission: Implement the submission logic: In addContact. js, use wx. cloud. database(). collection (‘contacts’). add() to add the new contact to the cloud database.

5.2 Backend Implementation

5.2.1 Implemention of Adding Operation

// cloud/functions/addContact/index.js
const cloud = require('wx-server-sdk');

cloud.init();
const db = cloud.database();

exports.main = async (event, context) => {
  const { name, phone, email, address } = event;  // Retrieve contact information from the event
  try {
    return await db.collection('contacts').add({
      data: {
        name,
        phone,
        email,
        address
      }
    });
  } catch (e) {
    return {
      error: e
    };
  }
};

5.2.2 Implemention of Modifying Operation

// cloud/functions/updateContact/index.js
const cloud = require('wx-server-sdk');

cloud.init();
const db = cloud.database();

exports.main = async (event, context) => {
  const { id, name, phone, email, address } = event;  // Get the contact information to be modified
  try {
    return await db.collection('contacts').doc(id).update({
      data: {
        name,
        phone,
        email,
        address
      }
    });
  } catch (e) {
    return {
      error: e
    };
  }
};

5.2.3 Implemention of Deleting Operation

// cloud/functions/deleteContact/index.js
const cloud = require('wx-server-sdk');

cloud.init();
const db = cloud.database();

exports.main = async (event, context) => {
  const { id } = event;  // Get the contact ID to be deleted
  try {
    return await db.collection('contacts').doc(id).remove();
  } catch (e) {
    return {
      error: e
    };
  }
};

5.2.4 Call Cloud Functions

// Adding Contact
wx.cloud.callFunction({
  name: 'addContact',
  data: {
    name: this.data.newContactName,
    phone: this.data.newContactPhone,
    email: this.data.newContactEmail,
    address: this.data.newContactAddress
  },
  success: res => {
    console.log('Contact added successfully', res);
    // Update page status
  },
  fail: err => {
    console.error('Failed to add contact', err);
  }
});

// Get contact list
wx.cloud.callFunction({
  name: 'loadContacts',
  success: res => {
    this.setData({
      contacts: res.result  // Update contact list
    });
  },
  fail: err => {
    console.error('Failed to retrieve contacts', err);
  }
});

6. Code Explanation

6.1 Frontend

  1. Structure and Layout:
  • By using the scroll view component to implement a scrolling view of the contact list, the user experience is enhanced
  • Use the wx: for loop to group contacts and display them alphabetically, making it easier for users to search.
  • Using the navigator component to redirect to the detailed information page by clicking on the contact name maintains the interface’s sense of hierarchy and logic.
<view class="navi">
  <view class="navitext">咖喱录</view>
</view>
<scroll-view class="contact" scroll-y="true" scroll-into-view="{{loc}}" style="height:{{screenHeight}}rpx">
  <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>
  </block>
</scroll-view>
  1. Data Processing and Display:
  • Retrieve cloud database instances through wx. cloud. database() and read contact data from the contacts collection.
  • After obtaining the data successfully, call the arrangeContact method to classify and sort the contacts.
  • Record error messages when a failure occurs for easy debugging and troubleshooting in the future.
loadContactsFromDatabase() {
  contactsCollection.field({ name: true, _id: true }).get({
    success: res => {
      let contacts = res.data;
      this.arrangeContact(contacts);
    },
    fail: err => {
      console.error('Failed to retrieve contacts from database:', err);
    }
  });
}
  1. Search Function:
  • Implement search function, update searchTerm instantly when user inputs and call filtering function.
  • In filterContacts, real-time filtering of contacts based on user input enables dynamic search.
  • Maintain data responsiveness and real-time performance to enhance user experience.
onSearchInput: function (e) {
  const searchTerm = e.detail.value.toLowerCase();
  this.setData({ searchTerm: searchTerm });
  this.filterContacts();
},

filterContacts: function () {
  const filteredContacts = this.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);
  
  this.setData({ filteredContacts: filteredContacts });
}

6.2 Backend

  1. Data Access:
  • Create a reference to the contacts collection for CRUD operations.
  • Make data operations more intuitive, and subsequent retrieval, addition, and deletion of contacts can be done through this collection reference.
const contactsCollection = db.collection('contacts');
  1. Data Query and Processing:
  • Use the. get() method to retrieve contact data from the database and specify to only retrieve the required fields.
  • After successful acquisition, organize the data and process it as needed; Record errors when processing failures for subsequent troubleshooting.
contactsCollection.field({ name: true, _id: true }).get({
  success: res => {
    let contacts = res.data;
    this.arrangeContact(contacts);
  },
  fail: err => {
    console.error('Failed to retrieve contacts from database:', err);
  }
});

7. Personal Journey and Learnings

  1. Frontend Learnings:
    During this project, I deepened my knowledge of WeChat’s Mini Program framework, specifically in structuring and optimizing a user interface (UI) for mobile. I learned to efficiently use .wxml and .wxss files to create intuitive layouts and styles tailored for small screens. Handling interactivity in .js files taught me about binding data and dynamically updating UI elements. I gained experience with scroll-view and conditional rendering for organizing contacts by alphabetical sections, refining my approach to implementing both visually appealing and user-friendly features. I also improved my understanding of front-end performance, learning how to balance visual design and usability.
  2. Backend Learnings and Database Skills:
    On the back end, I worked with WeChat’s cloud functions and databases, which streamlined data storage and retrieval. Through this, I gained hands-on experience with NoSQL databases and learned the importance of data structuring, efficient querying, and indexing to manage user data effectively. Implementing the contact storage in a way that integrates smoothly with the UI taught me about asynchronous operations and error handling. I also tackled issues such as data synchronization and managing updates across different devices, which helped me better understand cloud functions’ role in scalable applications.

8. Conclusion

This project has strengthened my full stack development skills, enabling me to effectively connect front-end and back-end. I have learned the importance of maintainable code, proper data processing, and user centered design. In addition, this experience has given me confidence to undertake more complex projects in the future.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值