当前位置:首页 > 文章列表 > 文章 > 前端 > 底层设计:轮询系统 - 边缘情况

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

来源:dev.to 2024-12-02 11:40:24 0浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《底层设计:轮询系统 - 边缘情况》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

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

目录

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

请先参考以下文章:

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

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

边缘情况处理

案例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 < 2) {
        return res.status(400).json({ message: "invalid input data. question and at least two options are required." });
    }

    try {
        const connection = await pool.getconnection();
        await connection.begintransaction();

        const [result] = await connection.execute(
            'insert into polls (current_version_id) values (null)'
        );

        const pollid = result.insertid;

        const [versionresult] = await connection.execute(
            'insert into poll_versions (poll_id, question) values (?, ?)',
            [pollid, question]
        );

        const versionid = versionresult.insertid;

        // update the current version in the polls table
        await connection.execute(
            'update polls set current_version_id = ? where poll_id = ?',
            [versionid, pollid]
        );

        const optionqueries = options.map(option => {
            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 < 2) {
        return res.status(400).json({ message: "invalid input data. at least two options are required." });
    }

    try {
        const connection = await pool.getconnection();
        await connection.begintransaction();

        // fetch the existing poll
        const [existingpoll] = await connection.execute(
            'select question from poll_versions where poll_id = (select current_version_id from polls where poll_id = ?)',
            [pollid]
        );

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

        const currentquestion = existingpoll[0].question;

        // check if the question has changed
        if (currentquestion !== question) {
            // create a new version since the question has changed
            const [versionresult] = await connection.execute(
                'insert into poll_versions (poll_id, question) values (?, ?)',
                [pollid, question]
            );

            const versionid = versionresult.insertid;

            // update the current version in the polls table
            await connection.execute(
                'update polls set current_version_id = ? where poll_id = ?',
                [versionid, pollid]
            );
        }

        // remove old options and insert new ones
        await connection.execute('delete from options where poll_id = ?', [pollid]);

        const optionqueries = options.map(option => {
            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

更多详情:

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

系统设计与zeeshanali

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

今天关于《底层设计:轮询系统 - 边缘情况》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
GORM 字段标签:Go 语法扩展还是 GORM 独有功能?GORM 字段标签:Go 语法扩展还是 GORM 独有功能?
上一篇
GORM 字段标签:Go 语法扩展还是 GORM 独有功能?
微信扫码登录后如何优雅地关闭弹窗并刷新主窗口?
下一篇
微信扫码登录后如何优雅地关闭弹窗并刷新主窗口?
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 笔灵AI生成答辩PPT:高效制作学术与职场PPT的利器
    笔灵AI生成答辩PPT
    探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
    16次使用
  • 知网AIGC检测服务系统:精准识别学术文本中的AI生成内容
    知网AIGC检测服务系统
    知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
    25次使用
  • AIGC检测服务:AIbiye助力确保论文原创性
    AIGC检测-Aibiye
    AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
    30次使用
  • 易笔AI论文平台:快速生成高质量学术论文的利器
    易笔AI论文
    易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
    42次使用
  • 笔启AI论文写作平台:多类型论文生成与多语言支持
    笔启AI论文写作平台
    笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
    35次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码