」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 底層設計:輪詢系統 - 使用 Nodejs

底層設計:輪詢系統 - 使用 Nodejs

發佈於2024-11-08
瀏覽:179

Low-Level Design: Polling System - Using Nodejs

Table of Contents

  1. Database Setup
    • MySQL Database Schema
    • ERD for the Polling System
  2. Backend Setup
    • Step 1: Initialize the Project
    • Step 2: Project Structure
  3. API Implementation
    • Step 1: Database Connection (db/db.js)
    • Step 2: Environment Variables (.env)
    • Step 3: Poll Controller (controllers/pollController.js)
    • Step 4: Poll Routes (routes/pollRoutes.js)
    • Step 5: Server Entry Point (index.js)
  4. Error Handling
  5. Testing
  6. Conclusion

Please refer to the article Polling System Basic Low-Level Design - I

Let's break down the entire process into detailed steps, including the database setup, API implementation using Node.js with Express, and interaction with MySQL. We will cover:

Database Setup

First, we'll define the schema for the MySQL database and create the necessary tables.

MySQL Database Schema

CREATE DATABASE polling_system;

USE polling_system;

CREATE TABLE polls (
    poll_id INT AUTO_INCREMENT PRIMARY KEY,
    question VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE options (
    option_id INT AUTO_INCREMENT PRIMARY KEY,
    poll_id INT,
    option_text VARCHAR(255) NOT NULL,
    FOREIGN KEY (poll_id) REFERENCES polls(poll_id) ON DELETE CASCADE
);

CREATE TABLE votes (
    vote_id INT AUTO_INCREMENT PRIMARY KEY,
    poll_id INT,
    user_id VARCHAR(255) NOT NULL,
    option_id INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (poll_id) REFERENCES polls(poll_id) ON DELETE CASCADE,
    FOREIGN KEY (option_id) REFERENCES options(option_id) ON DELETE CASCADE
);
  • polls table: Stores poll information with a unique identifier, question, and creation timestamp.

  • options table: Stores the options associated with a poll, linked via poll_id.

  • votes table: Records each vote, linking to the poll, option, and user.

    ERD for the Polling System

Entities:

  1. Polls: Represents the poll itself, with attributes like poll_id and question.
  2. Options: Represents the options available for each poll, with attributes like option_id and option_text.
  3. Votes: Represents the votes cast by users, with attributes like vote_id, user_id, and timestamps.

Relationships:

  1. One-to-Many between Polls and Options: Each poll can have multiple options.
  2. Many-to-One between Votes and Options: Each vote is associated with one option.
  3. Many-to-One between Votes and Polls: Each vote is linked to a specific poll.

Here’s a description of the ERD:

  1. Polls Table:

    • poll_id (Primary Key)
    • question
    • created_at
  2. Options Table:

    • option_id (Primary Key)
    • poll_id (Foreign Key referencing polls.poll_id)
    • option_text
  3. Votes Table:

    • vote_id (Primary Key)
    • poll_id (Foreign Key referencing polls.poll_id)
    • option_id (Foreign Key referencing options.option_id)
    • user_id
    • created_at

The relationships would be represented with lines between the entities:

  • PollsOptions: One poll can have many options.
  • OptionsVotes: One option can have many votes.
  • PollsVotes: One poll can have many votes.

Backend Setup

Let's set up a Node.js project using Express and MySQL.

Step 1: Initialize the Project

mkdir polling-system
cd polling-system
npm init -y
npm install express mysql2 dotenv

  • express: A web framework for Node.js.
  • mysql2: A MySQL client for Node.js.
  • dotenv: For managing environment variables.

Step 2: Project Structure

Create a basic structure for the project:

polling-system/
│
├── .env
├── index.js
├── db/
│   └── db.js
├── routes/
│   └── pollRoutes.js
└── controllers/
    └── pollController.js

API Implementation

Step 1: Database Connection

File - db/db.js

const mysql = require('mysql2/promise');
require('dotenv').config();

const pool = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

module.exports = pool;

Step 2: Environment Variables

File - .env

DB_HOST=localhost
DB_USER=root
DB_PASSWORD=yourpassword
DB_NAME=polling_system
PORT=3000

Step 3: Poll Controller

File - controllers/pollController.js

This file will implement all the necessary CRUD operations for the polling system.

const pool = require('../db/db');

// Create Poll
exports.createPoll = async (req, res) => {
    const { question, options } = req.body;

    if (!question || !options || !Array.isArray(options) || options.length  {
            return connection.execute(
                'INSERT INTO options (poll_id, option_text) VALUES (?, ?)',
                [pollId, option]
            );
        });

        await Promise.all(optionQueries);

        await connection.commit();
        connection.release();

        res.status(201).json({ pollId, message: "Poll created successfully." });

    } catch (error) {
        console.error("Error creating poll:", error.message);
        res.status(500).json({ message: "Error creating poll." });
    }
};

// Update Poll
exports.updatePoll = async (req, res) => {
    const { pollId } = req.params;
    const { question, options } = req.body;

    if (!pollId || !question || !options || !Array.isArray(options) || options.length  {
            return connection.execute(
                'INSERT INTO options (poll_id, option_text) VALUES (?, ?)',
                [pollId, option]
            );
        });

        await Promise.all(optionQueries);

        await connection.commit();
        connection.release();

        res.status(200).json({ message: "Poll updated successfully." });

    } catch (error) {
        console.error("Error updating poll:", error.message);
        res.status(500).json({ message: "Error updating poll." });
    }
};

// Delete Poll
exports.deletePoll = async (req, res) => {
    const { pollId } = req.params;

    try {
        const connection = await pool.getConnection();

        const [result] = await connection.execute(
            'DELETE FROM polls WHERE poll_id = ?',
            [pollId]
        );

        connection.release();

        if (result.affectedRows === 0) {
            return res.status(404).json({ message: "Poll not found." });
        }

        res.status(200).json({ message: "Poll deleted successfully." });

    } catch (error) {
        console.error("Error deleting poll:", error.message);
        res.status(500).json({ message: "Error deleting poll." });
    }
};

// Vote in Poll
exports.voteInPoll = async (req, res) => {
    const { pollId } = req.params;
    const { userId, option } = req.body;

    if (!userId || !option) {
        return res.status(400).json({ message: "User ID and option are required." });
    }

    try {
        const connection = await pool.getConnection();

        const [userVote] = await connection.execute(
            'SELECT * FROM votes WHERE poll_id = ? AND user_id = ?',
            [pollId, userId]
        );

        if (userVote.length > 0) {
            connection.release();
            return res.status(400).json({ message: "User has already voted." });
        }

        const [optionResult] = await connection.execute(
            'SELECT option_id FROM options WHERE poll_id = ? AND option_text = ?',
            [pollId, option]
        );

        if (optionResult.length === 0) {
            connection.release();
            return res.status(404).json({ message: "Option not found." });
        }

        const optionId = optionResult[0].option_id;

        await connection.execute(
            'INSERT INTO votes (poll_id, user_id, option_id) VALUES (?, ?, ?)',
            [pollId, userId, optionId]
        );

        connection.release();

        res.status(200).json({ message: "Vote cast successfully." });

    } catch (error) {
        console.error("Error casting vote:", error.message);
        res.status(500).json({ message: "Error casting vote." });
    }
};

// View Poll Results
exports.viewPollResults = async (req, res) => {
    const { pollId } = req.params;

    try {
        const connection = await pool.getConnection();

        const [poll] = await connection.execute(
            'SELECT * FROM polls WHERE poll_id = ?',
            [pollId]
        );

        if (poll.length === 0) {
            connection.release();
            return res.status(404).json({ message: "Poll not found." });
        }

        const [options] = await connection.execute(
            'SELECT option_text, COUNT(votes.option_id) as vote_count FROM options '  
            'LEFT JOIN votes ON options.option_id = votes.option_id '  
            'WHERE options.poll_id = ? GROUP BY options.option_id',
            [pollId]
        );

        connection.release();

        res.status(200).json({
            pollId: poll[0].poll_id,
            question: poll[0].question,
            results: options.reduce((acc, option) => {
                acc[option.option_text] = option.vote_count;
                return acc;
            }, {})
        });

    } catch (error) {
        console.error("Error viewing poll results:", error.message);
        res.status(500).json({ message: "Error viewing poll results." });
    }
};

Step 4: Poll Routes

File - routes/pollRoutes.js
Define the routes for each API endpoint:

const express = require('express');
const router = express.Router();
const pollController = require('../controllers/pollController');

//

 Routes
router.post('/polls', pollController.createPoll);
router.put('/polls/:pollId', pollController.updatePoll);
router.delete('/polls/:pollId', pollController.deletePoll);
router.post('/polls/:pollId/vote', pollController.voteInPoll);
router.get('/polls/:pollId/results', pollController.viewPollResults);

module.exports = router;

Step 5: Server Entry Point

File - index.js
Finally, set up the server:

const express = require('express');
const pollRoutes = require('./routes/pollRoutes');
require('dotenv').config();

const app = express();
app.use(express.json());

// Routes
app.use('/api', pollRoutes);

// Error Handling Middleware
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ message: "Internal server error" });
});

// Start Server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Error Handling

Each method includes error handling for common issues like invalid input, duplicate votes, missing poll or option, and server errors.

  • Input Validation: Checks are performed to ensure that the inputs are valid, such as checking if the required fields are present and properly formatted.
  • Transaction Management: For operations involving multiple queries (e.g., creating or updating polls), transactions are used to ensure consistency.

Testing

Test each endpoint using tools like Postman or curl.

  • Create Poll: POST /api/polls with a JSON body containing question and an array of options.
  • Update Poll: PUT /api/polls/:pollId with updated question and options.
  • Delete Poll: DELETE /api/polls/:pollId.
  • Vote in Poll: POST /api/polls/:pollId/vote with userId and option.
  • View Poll Results: GET /api/polls/:pollId/results.

Conclusion

This is a comprehensive modular implementation of an online polling system using Node.js, Express, and MySQL. It handles the basic CRUD operations and ensures data consistency with transactions. It also includes basic error handling to make the API more robust and user-friendly.

Please refer to the article Polling System Basic Low-Level Design - I

More Details:

Get all articles related to system design
Hastag: SystemDesignWithZeeshanAli

systemdesignwithzeeshanali

Git: https://github.com/ZeeshanAli-0704/SystemDesignWithZeeshanAli

版本聲明 本文轉載於:https://dev.to/zeeshanali0704/low-level-design-polling-system-2-2j21?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何在 PHP 中列印單引號內的變數?
    如何在 PHP 中列印單引號內的變數?
    無法直接回顯帶有單引號的變數需要在單引號字串中列印變數?直接這樣做是不可能的。 如何在單引號內列印變數:方法1:使用串聯追加 為此,請使用點運算子將變數連接到字串上:echo 'I love my ' . $variable . '.';此方法將變數追加到字串中。 方法 2:使用雙引號或者,在字串並...
    程式設計 發佈於2024-12-24
  • std::vector 與普通數組:何時效能真正重要?
    std::vector 與普通數組:何時效能真正重要?
    std::vector 與普通數組:性能評估雖然人們普遍認為std::vector 的操作與數組類似,但最近的測試對這一概念提出了挑戰。在本文中,我們將研究 std::vector 和普通數組之間的效能差異,並闡明根本原因。 為了進行測試,實施了一個基準測試,其中涉及重複建立和修改大型陣列像素物件。...
    程式設計 發佈於2024-12-24
  • 儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    解決PHP 中的POST 請求故障在提供的程式碼片段:action=''而非:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"檢查$_POST陣列:表單提交後使用 var_dump 檢查 $_POST 陣列的內容...
    程式設計 發佈於2024-12-24
  • 插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入記錄時如何解決「一般錯誤:2006 MySQL 伺服器已消失」介紹:將資料插入MySQL 資料庫有時會導致錯誤「一般錯誤:2006 MySQL 伺服器已消失」。當與伺服器的連線遺失時會出現此錯誤,通常是由於 MySQL 配置中的兩個變數之一所致。 解決方案:解決此錯誤的關鍵是調整wait_tim...
    程式設計 發佈於2024-12-24
  • HTML 格式標籤
    HTML 格式標籤
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    程式設計 發佈於2024-12-24
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-12-24
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1 和 $array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建...
    程式設計 發佈於2024-12-24
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-12-24
  • 為什麼雙精確度的小數位數比宣傳的 15 位多?
    為什麼雙精確度的小數位數比宣傳的 15 位多?
    雙精度和小數位精度在電腦程式設計中,雙精度資料型態通常被假定為具有 15 位小數的近似精度。但是,某些數字表示形式(例如 1.0/7.0)在變數內部表示時似乎具有更高的精確度。本文將探討為什麼會發生這種情況,以及為什麼精確度通常被描述為小數點後 15 位左右。 內部表示IEEE 雙精度數有 53 個...
    程式設計 發佈於2024-12-24
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    程式設計 發佈於2024-12-24
  • 箭頭函數中的隱式回傳與明確傳回:何時需要大括號?
    箭頭函數中的隱式回傳與明確傳回:何時需要大括號?
    箭頭函數中的花括號:隱式與明確返回箭頭函數可以用兩種方式編寫:帶或不帶花括號。當大括號不存在時,函數體被認為是“簡潔體”,並且隱式傳回其中的最後一個表達式。 帶有簡潔體的隱式回傳In不帶大括號的範例:state.map(one => oneTodo(one, action))The函數立即傳回...
    程式設計 發佈於2024-12-24
  • 為什麼使用「transform:scale()」後我的文字在 Chrome 中變得模糊?
    為什麼使用「transform:scale()」後我的文字在 Chrome 中變得模糊?
    變換後Chrome 中的文字模糊:scale()在最近的Chrome 更新中,出現了一個特殊問題,即使用CSS 轉換呈現的文字:scale() 屬性顯得模糊。使用以下特定程式碼時已觀察到此問題:@-webkit-keyframes bounceIn { 0% { opacity: 0; ...
    程式設計 發佈於2024-12-24
  • 如何在 GoLang 中實作 MDC 日誌記錄?
    如何在 GoLang 中實作 MDC 日誌記錄?
    GoLang 中的 MDC LoggingJava 的 MDC Logging 依賴線程本地存儲,這在 GoLang 中不可用。然而,透過堆疊中的線程化 Context 可以實現類似的功能。 Java MDC 依賴線程本地存儲,這是 Go 所不具備的。最接近的是透過堆疊線程化 Context,這正在...
    程式設計 發佈於2024-12-23
  • 為什麼我的隨機數在循環內是一致的?
    為什麼我的隨機數在循環內是一致的?
    理解迭代中一致的隨機數在提供的程式碼片段中,可以觀察到循環迭代中產生的隨機數保持一致。具體來說,儘管循環旨在產生唯一值,但「carSetter」和「decider」變數在 15 次迭代中保留相同的值。 此行為是由於循環內放置了 srand(time(0)) 造成的。它決定後續呼叫 rand() 時傳...
    程式設計 發佈於2024-12-23
  • Java中處理InputMismatchException時如何防止無限迴圈?
    Java中處理InputMismatchException時如何防止無限迴圈?
    InputMismatchException的try/catch區塊中的無限循環:解決方案您的Java程式在嘗試處理InputMismatchException時遇到無限循環/catch 區塊,同時從使用者取得整數輸入。此行為源自於這樣的事實:在捕獲 InputMismatchException 後...
    程式設計 發佈於2024-12-23

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3