卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章76570本站已运行4323

底层设计:轮询系统 - 边缘情况

底层设计:轮询系统 - 边缘情况

目录

案例 1 - 处理更新的版本控制
情况 2 - pollid 作为 uuid 而不是主键
情况 3 - 选项为空或无效
案例 4 - 重复选项
案例 5 - 问题长度限制
案例 6 - 投票过期

请先参考以下文章:

  1. 底层设计:投票系统:基本

  2. 底层设计:轮询系统 - 使用 node.js 和 sql

    点击下载“C盘瘦身工具,一键清理C盘”;

边缘情况处理

案例1

要管理投票问题和选项的更新,同时保留与同一投票 id 关联的先前详细信息,您可以实现版本控制系统。这种方法允许您跟踪每次民意调查的历史数据,确保即使在更新后也保留旧的详细信息。

第 1 步:数据库架构更改

  1. 更新投票表

    • 将 current_version_id 列添加到 polls 表中以跟踪投票的最新版本。
  2. 创建投票版本表

    • 创建一个新表来存储民意调查的历史版本。

更新的数据库架构

create database polling_system;

use polling_system;

create table polls (
    poll_id int auto_increment primary key,
    current_version_id int,
    created_at timestamp default current_timestamp,
    foreign key (current_version_id) references poll_versions(version_id) on delete set null
);

create table poll_versions (
    version_id int auto_increment primary key,
    poll_id int,
    question varchar(255) not null,
    created_at timestamp default current_timestamp,
    foreign key (poll_id) references polls(poll_id) on delete cascade
);

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
);

第 2 步:api 实施变更

更新轮询控制器

修改 updatepoll 方法,在创建新版本之前检查问题是否发生变化。

文件:controllers/pollcontroller.js
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 || !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);
        await connection.rollback();
        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." });
    }
};

第 3 步:更新投票路线

确保在 pollroutes.js 中正确定义路由。

文件:routes/pollroutes.js
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;

变更摘要

  1. 数据库:

    • 更新了投票表以包含 current_version_id。
    • 创建了 poll_versions 表来跟踪问题版本。
    • 选项和投票表保持不变。
  2. api:

    • 创建了一个新的 createpoll 方法来初始化民意调查和版本。
    • 更新了 updatepoll 方法以在创建新版本之前检查问题更改。
    • 添加了投票和查看投票结果的方法。
  3. 路线:

    • 确保定义所有必要的路由来处理民意调查创建、更新、投票和结果。

案例2

处理 pollid 需要是 uuid(通用唯一标识符)的场景。

以下是在轮询系统中为 thepollid 实现 uuid 的步骤,无需提供代码:

为投票 id 实施 uuid 的步骤

  1. ** 数据库架构更新:**

    • 修改 polls、poll_versions、options 和 votes 表,以使用 char(36) 作为 poll_id 而不是整数。
    • 创建一个新的 poll_versions 表来存储由 uuid 链接的投票问题和选项的历史版本。
  2. ** uuid 生成:**

    • 决定生成uuid的方法。您可以使用应用程序环境中的库或内置函数来创建uuid。
  3. ** 创建投票逻辑:**

    • 创建新投票时,生成一个 uuid 并将其用作 poll_id。
    • 将新的投票记录插入投票表中。
    • 将初始问题插入 poll_versions 表并将其与生成的 uuid 链接。
  4. ** 更新投票逻辑:**

    • 更新投票时:
  5. 检查问题是否已更改。

    • 如果问题已更改,请在poll_versions 表中创建一个新版本条目来存储旧问题和选项。
    • 根据需要使用新问题和选项更新投票表。
  6. ** 投票逻辑:**

    • 更新投票机制,确保使用uuid作为poll_id。
  7. 验证投票请求中提供的 uuid 是否存在于 polls 表中。

  8. ** api 更新:**

    • 修改 api 端点以接受并返回 poll_id 的 uuid。
    • 确保所有 api 操作(创建、更新、删除、投票)一致引用 uuid 格式。
  9. ** 测试:**

    • 彻底测试应用程序,确保在所有场景(创建、更新、投票和检索投票结果)中正确处理 uuid。
  10. ** 文档:**

    • 更新您的 api 文档以反映 poll_id 格式的更改以及与版本控制和 uuid 使用相关的任何新行为。

按照以下步骤,您可以在轮询系统中成功实现 pollid 的 uuid,同时确保数据完整性和历史跟踪。


案例3

空或无效选项

验证方法:

  • api 输入验证: 在 api 端点中实施检查,以验证请求正文中提供的选项不为空并满足特定条件(例如,如果不允许,则不得使用特殊字符)。
  • 反馈机制:如果选项无效或为空,向用户提供清晰的错误消息,指导他们纠正输入。

案例4

重复选项

唯一性检查:

  • 预插入验证: 在将选项添加到投票之前,检查数据库中现有选项是否有重复项。这可以通过使用轮询 id 查询选项表并将其与新选项进行比较来完成。
  • 用户反馈:如果检测到重复选项,则返回一条有意义的错误消息,通知用户哪些选项是重复的,从而允许他们相应地修改其输入。

案例5

问题长度限制

字符限制:

  • api 验证: 设置 api 中投票问题和选项的最大字符限制。这可以通过在创建和更新过程中检查问题的长度和每个选项来完成。
  • 用户界面反馈:实施客户端验证,以便在用户输入时超出字符限制时向用户提供即时反馈,增强用户体验。

案例6

投票过期

过期机制:

  • 时间戳管理: 将时间戳字段添加到投票表中,以记录每个投票的创建时间,还可以选择另一个字段来记录到期日期。
  • 计划检查: 实施后台作业或 cron 任务,定期检查过期的轮询并将其在数据库中标记为非活动状态。这还可以包括阻止对过期民意调查进行投票。
  • 用户通知:(可选)通知投票创建者和参与者即将到期的日期,以便他们在投票变为非活动状态之前参与投票。

请先参考以下文章:

  1. 底层设计:投票系统:基本

  2. 底层设计:轮询系统 - 使用 node.js 和 sql

    点击下载“C盘瘦身工具,一键清理C盘”;

更多详情:

获取所有与系统设计相关的文章
标签:systemdesignwithzeeshanali

系统设计与zeeshanali

git:https://github.com/zeeshanali-0704/systemdesignwithzeeshanali

卓越飞翔博客
上一篇: Go 框架中防止跨站脚本攻击的指南
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏