bot界面 增删改查

需求分析和准备工作

实现这么一个页面

a71ee7973dfc6523fcca6aeb0d33c9c5-7dce4a18

主要是对bot的一个增删改查操作

前提就是创一个数据表来存储它

实体类

在数据库中创建表bot

表中包含的列:

id: int:非空、自动增加、唯一、主键

user_id: int:非空

注意:在pojo中需要定义成userId,在queryWrapper中的名称仍然为user_id

title: varchar(100)

description: varchar(300)

content:varchar(10000)

rating: int:默认值为1500

createtime: datetime

pojo中定义日期格式的注解:@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")

modifytime: datetime

pojo中定义日期格式的注解:@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")

CREATE TABLE `kob`.`bot`  (
  `id` int NOT NULL AUTO_INCREMENT,
  `user_id` int NOT NULL,
  `title` varchar(100) NULL,
  `description` varchar(300) NULL,
  `content` varchar(10000) NULL,
  `rating` int NULL DEFAULT 1500,
  `createtime` datetime NULL,
  `modifytime` datetime NULL,
  PRIMARY KEY (`id`)
);
image-3ed75f77

pojo中

package com.zwnsyw.backend.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Bot {
    @TableId(type = IdType.AUTO)
    private Integer id;
    private Integer userId;//注意 数据库中下划线命名对应pojo驼峰命名
    private String title;
    private String description;
    private String content;
    private Integer rating;
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date createtime;
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date modifytime;
}

mapper

package com.zwnsyw.backend.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zwnsyw.backend.pojo.Bot;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface BotMapper extends BaseMapper<Bot> {
}

增删改查api

已经熟悉了 三部曲 service、serviceimpl、controller

先写接口 再写实现 再写调用

Service

image-457bbc8b
AddService
package com.zwnsyw.backend.service.bot;

import java.util.Map;

public interface AddService {
    public Map<String,String> add(Map<String,String> data);
}
RemoveService
package com.zwnsyw.backend.service.bot;

import java.util.Map;

public interface RemoveService {
    Map<String,String> remove(Map<String,String> data);
}
UpdateService
package com.zwnsyw.backend.service.bot;

import java.util.Map;

public interface UpdateService {
    Map<String,String> update(Map<String,String> data);
}
GetListService
package com.zwnsyw.backend.service.bot;

import com.zwnsyw.backend.pojo.Bot;

import java.util.List;

public interface GetListService {
    List<Bot> getList();
}

ServiceImpl

三部曲 @Service 、 Implements ?Service、 alt+insert实现方法

AddServiceImpl
package com.zwnsyw.backend.service.impl.bot;

import com.zwnsyw.backend.mapper.BotMapper;
import com.zwnsyw.backend.pojo.Bot;
import com.zwnsyw.backend.pojo.User;
import com.zwnsyw.backend.service.bot.AddService;
import com.zwnsyw.backend.service.impl.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AddServiceImpl implements AddService {

    @Autowired
    private BotMapper botMapper;

    @Override
    public Map<String, String> add(Map<String, String> data) {
        //要知道是哪个用户在操作 需要先取出用户信息 从token中得到 所以比较麻烦
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        //需要拿到哪些数据 看表来
        //id自增不用管 user_id刚取得了
        //title需要传来 描述需要传来 内容需要传来
        //分数默认1500不用管 创建时间是现在不用管 修改时间默认是现在不用管
        String title = data.get("title");
        String description = data.get("description");
        String content = data.get("content");

        Map<String,String> map = new HashMap<>();

        //加一系列判断
        if(title == null || title.length() == 0){
            map.put("error_message","标题不能为空");
            return map;
        }
        if(title.length() > 100){
            map.put("error_message","标题长度不能大于100");
            return map;
        }

        //描述可以为空
        if(description == null || description.length()==0){
            description="这个用户很懒,什么也没留下~";
        }

        if(description.length()>300){
            map.put("error_message","Bot的描述不能超过300");
            return map;
        }

        if(content == null || content.length() == 0){
            map.put("error_message","代码不能为空");
            return map;
        }
        if(content.length()>10000){
            map.put("error_message","代码长度不能超过10000");
            return map;
        }

        Date now=new Date();
        Bot bot = new Bot(null,user.getId(),title,description,content,1500,now,now);

        //添加到数据库中 需要注入接口 BotMapper
        botMapper.insert(bot);
        map.put("error_message","success");

        return map;
    }
}
RemoveServiceImpl
package com.zwnsyw.backend.service.impl.bot;

import com.zwnsyw.backend.mapper.BotMapper;
import com.zwnsyw.backend.pojo.Bot;
import com.zwnsyw.backend.pojo.User;
import com.zwnsyw.backend.service.bot.RemoveService;
import com.zwnsyw.backend.service.impl.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RemoveServiceImpl implements RemoveService {
    @Autowired
    private BotMapper botMapper;

    @Override
    public Map<String, String> remove(Map<String, String> data) {
        //取出当前用户 用于鉴权 是否有权限删除该bot
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        int botId = Integer.parseInt(data.get("botId"));
        Bot bot = botMapper.selectById(botId);

        Map<String,String>  map = new HashMap<>();
        if(bot == null){
            map.put("error_message","Bot不存在或已被删除");
            return map;
        }
        if(!bot.getUserId().equals(user.getId())){
            map.put("error_message","没有权限删除Bot");
            return map;
        }

        botMapper.deleteById(botId);
        map.put("error_message","success");

        return map;
    }
}
UpdateServiceImpl
package com.zwnsyw.backend.service.impl.bot;

import com.zwnsyw.backend.mapper.BotMapper;
import com.zwnsyw.backend.pojo.Bot;
import com.zwnsyw.backend.pojo.User;
import com.zwnsyw.backend.service.bot.UpdateService;
import com.zwnsyw.backend.service.impl.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UpdateServiceImpl implements UpdateService {
    @Autowired
    private BotMapper botMapper;

    @Override
    public Map<String, String> update(Map<String, String> data) {
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        //更新谁 —— botId
        //更新哪些数据 user_id不会变 title会变 描述和内容会变 分数不能变 创建时间不能变 修改时间自动变
        int botId = Integer.parseInt(data.get("botId"));

        String title = data.get("title");
        String description = data.get("description");
        String content = data.get("content");

        Map<String,String> map = new HashMap<>();

        //加一系列判断
        if(title == null || title.length() == 0){
            map.put("error_message","标题不能为空");
            return map;
        }
        if(title.length() > 100){
            map.put("error_message","标题长度不能大于100");
            return map;
        }

        //描述可以为空
        if(description == null || description.length()==0){
            description="这个用户很懒,什么也没留下~";
        }

        if(description.length()>300){
            map.put("error_message","Bot的描述不能超过300");
            return map;
        }

        if(content == null || content.length() == 0){
            map.put("error_message","代码不能为空");
            return map;
        }
        if(content.length()>10000){
            map.put("error_message","代码长度不能超过10000");
            return map;
        }

        Bot bot = botMapper.selectById(botId);
        if(bot == null){
            map.put("error_message","Bot不存在或已被删除");
            return map;
        }

        if(!bot.getUserId().equals(user.getId())){
            map.put("error_message","没权限修改该Bot");
            return map;
        }

        Bot newbot = new Bot(
                bot.getId(),
                user.getId(),
                title,
                description,
                content,
                bot.getRating(),
                bot.getCreatetime(),
                new Date()
        );

        botMapper.updateById(newbot);
        map.put("error_message","success");

        return map;
    }
}
GetListServiceImpl
package com.zwnsyw.backend.service.impl.bot;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zwnsyw.backend.mapper.BotMapper;
import com.zwnsyw.backend.pojo.Bot;
import com.zwnsyw.backend.pojo.User;
import com.zwnsyw.backend.service.bot.GetListService;
import com.zwnsyw.backend.service.impl.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GetListServiceImpl implements GetListService {
    @Autowired
    private BotMapper botMapper;

    @Override
    public List<Bot> getList() {
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        QueryWrapper<Bot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());

        return botMapper.selectList(queryWrapper);
    }
}

controller

三部曲 @RestController 注入接口@Autowired ?Service get/postMapping(接口地址) @RequestParam 绑定数据

AddController
package com.zwnsyw.backend.controller.user.bot;

import com.zwnsyw.backend.service.bot.AddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class AddController {
    @Autowired
    private AddService addService;

    @PostMapping("/user/bot/add/")
    public Map<String,String> add(@RequestParam Map<String,String> data){
        return addService.add(data);
    }
}
test
<template>
    <ContentField>
         我的bot
    </ContentField>
 </template>

 
     import ContentField from '../../../components/ContentField.vue'
     import $ from 'jquery'
     import { useStore } from "vuex";

     export default{
        components:{
             ContentField
        },
        setup(){
            const store = useStore();
            $.ajax({
              url: "http://localhost:3000/user/bot/add/",
              type: "post",
              data:{
                title:"Bot的标题",
                description:"Bot的描述",
                content:"Bot的代码",
              },
              headers:{
                Authorization:"Bearer " + store.state.user.token,
              },
              success(resp){
                console.log(resp);
              },
              error(resp){
                console.log(resp);
              }
            })
        }
     }
 

 

 
image-823326d3 image-6890445f
RemoveController
 package com.zwnsyw.backend.controller.user.bot;

import com.zwnsyw.backend.service.bot.RemoveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class RemoveController {
    @Autowired
    private RemoveService removeService;

    @PostMapping("/user/bot/remove/")
    public Map<String,String> remove(@RequestParam Map<String,String> data){
        return removeService.remove(data);
    }

}
test
$.ajax({
            url: "http://localhost:3000/user/bot/remove/",
            type: "post",
            data:{
                botId:5,
            },
            headers:{
              Authorization:"Bearer " + store.state.user.token,
            },
            success(resp){
              console.log(resp);
            },
            error(resp){
              console.log(resp);
            }
          })
image-d1e27534 image-2edfb08a image-065b83e3
UpdateController
package com.zwnsyw.backend.controller.user.bot;

import com.zwnsyw.backend.service.bot.UpdateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class UpdateController {
    @Autowired
    private UpdateService updateService;

    @PostMapping("/user/bot/update/")
    public Map<String, String> update(@RequestParam Map<String, String> data) {
        return updateService.update(data);
    }
}
test
$.ajax({
            url: "http://localhost:3000/user/bot/update/",
            type: "post",
            data:{
                botId : 1,
                title:"修改Bot的标题",
                description:"修改Bot的描述",
                content:"修改Bot的代码",
            },
            headers:{
              Authorization:"Bearer " + store.state.user.token,
            },
            success(resp){
              console.log(resp);
            },
            error(resp){
              console.log(resp);
            }
          })
image-e38e8515 image-6712a2be
GetListController
package com.zwnsyw.backend.controller.user.bot;

import com.zwnsyw.backend.pojo.Bot;
import com.zwnsyw.backend.service.bot.GetListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class GetListController {
    @Autowired
    private GetListService getListService;

    @GetMapping("/user/bot/getlist/")
    public List<Bot> getList(){
        return getListService.getList();
    }
}
test
$.ajax({
            url: "http://localhost:3000/user/bot/getlist/",
            type: "get",
            headers:{
              Authorization:"Bearer " + store.state.user.token,
            },
            success(resp){
              console.log(resp);
            },
            error(resp){
              console.log(resp);
            }
          })
image-bc8625a8

前端部分

大概布局

a71ee7973dfc6523fcca6aeb0d33c9c5-7dce4a18
<template>

  <div class="container">

    <div class="card">

      <div class="card-header">

        <span class="card-header-name">我的Bots</span>

        <button

            class="add-bot float-end"

            data-bs-toggle="modal"

            data-bs-target="#add-bot-button"

        >

          <span>+ Bot</span>

        </button>

        <!-- Modal -->

        <div class="modal fade" id="add-bot-button" tabindex="-1">

          <div class="modal-dialog modal-lg">

            <div class="modal-content">

              <div class="modal-header">

                <h5 class="modal-title">Create Bot</h5>

                <button

                    type="button"

                    class="btn-close"

                    data-bs-dismiss="modal"

                    aria-label="Close"

                ></button>

              </div>

              <div class="modal-body">

                <div class="mb-2">

                  <label for="bot-title" class="form-label">Bot Title</label>

                  <input

                      v-model="bot_add.title"

                      type="text"

                      class="form-control"

                      id="bot-title"

                      placeholder="名称"

                  />

                </div>

                <div class="mb-2">

                  <label for="description" class="form-label text-left">Description</label>

                  <textarea

                      v-model="bot_add.description"

                      class="form-control"

                      id="description"

                      placeholder="简介"

                      rows="2"

                  ></textarea>

                </div>

                <div class="row">

                  <div class="mb-2 col-6">

                    <label for="language" class="form-label">Language</label>

                    <select

                        v-model="bot_add.language"

                        class="form-select"

                        aria-label="Default select example"

                    >

                      <option selected>cpp</option>

                      <option>java</option>

                      <option>python3</option>

                      <option>python</option>

                    </select>

                  </div>

                  <div class="mb-2 col-6">

                    <label for="game" class="form-label">Game</label>

                    <select

                        v-model="bot_add.game"

                        class="form-select"

                        aria-label="Default select example"

                    >

                      <option selected>snake</option>

                      <option>reversi</option>

                    </select>

                  </div>

                </div>

                <div class="mb-2">

                  <label for="code" class="form-label">Code</label>

                  <a

                      class="code-template"

                      target="_blank"

                      href="https://www.yuque.com/docs/share/679878f3-95f6-4827-b41f-513852ac97a0?#%20%E3%80%8ABot%E4%BB%A3%E7%A0%81%E6%A8%A1%E6%9D%BF%E3%80%8B"

                  >代码模板</a

                  >

                  <VAceEditor

                      v-model:value="bot_add.content"

                      lang="c_cpp"

                      theme="textmate"

                      style="height: 235px; width: 100%;"

                      :options="{

                      fontSize: 16,

                      enableBasicAutocompletion: true,

                      enableSnippets: true,

                      enableLiveAutocompletion: true,

                      showPrintMargin: false,

                      highlightActiveLine: true,

                    }"

                  />

                </div>

              </div>

              <div class="modal-footer">

                <div class="error-msg">{{ error_msg }}</div>

                <button

                    type="button"

                    class="btn btn-secondary"

                    data-bs-dismiss="modal"

                >

                  取消

                </button>

                <button

                    type="button"

                    class="btn btn-primary"

                    @click="add_bot_event()"

                >

                  提交

                </button>

              </div>

            </div>

          </div>

        </div>

      </div>

      <div class="card-body">

        <table class="table" style="text-align: center">

          <thead class="table-dark bot-th">

          <tr>

            <th>序号</th>

            <th>游戏类型</th>

            <th>名称</th>

            <th>语言</th>

            <th>创建时间</th>

            <th>修改时间</th>

            <th>操作</th>

          </tr>

          </thead>

          <tbody>

          <tr v-for="(bot, index) in bots" :key="bot.id" class="bot-tr">

            <td>{{ index + 1 }}</td>

            <td>{{ bot.game }}</td>

            <td>{{ bot.title }}</td>

            <td>{{ bot.language }}</td>

            <td>{{ bot.createTime }}</td>

            <td>{{ bot.updateTime }}</td>

            <td>

              <button

                  class="update-bot"

                  data-bs-toggle="modal"

                  :data-bs-target="'#update-bot-modal-' + bot.id"

                  :id="'update_button' + bot.id"

              >

                <span>修改</span>

              </button>

              <button

                  class="remove-bot"

                  data-bs-toggle="modal"

                  data-bs-target="#delete_bot"

                  @click="confirm_bot_id(bot.id)"

              >

                <span style="color: white">删除</span>

              </button>

              <div

                  class="modal fade"

                  id="delete_bot"

                  tabindex="-1"

                  aria-labelledby="exampleModalLabel"

                  aria-hidden="true"

              >

                <div class="modal-dialog modal-dialog-centered">

                  <div

                      class="modal-content"

                      style="

                        background-color: white;

                        width: 340px;

                        margin: 0 auto;

                      "

                  >

                    <div class="modal-header">

                      <img

                          src="https://cdn.acwing.com/media/article/image/2022/09/02/36510_233881192a-热门.png"

                          alt="警告!"

                          style="height: 20px; margin: 0 auto"

                      />

                    </div>

                    <div

                        class="modal-body notice_msg"

                        style="margin: 0 auto; color: #838383"

                    >

                      你确定删除吗?

                    </div>

                    <div class="modal-footer" style="margin: 0 auto">

                      <button

                          type="button"

                          class="btn delete_cancel"

                          data-bs-dismiss="modal"

                          style="background-color: #f0f0f0; border-style: none"

                      >

                        取消

                      </button>

                      <button

                          type="button"

                          class="btn delete_confrim"

                          style="

                            background-color: #d9534f;

                            color: white;

                            border-style: none;

                          "

                          @click="remove_bot_event()"

                      >

                        删除

                      </button>

                    </div>

                  </div>

                </div>

              </div>

              <div

                  class="modal fade"

                  :id="'update-bot-modal-' + bot.id"

                  tabindex="-1"

              >

                <div class="modal-dialog modal-lg">

                  <div class="modal-content">

                    <div class="modal-header">

                      <h5 class="modal-title">Update Bot</h5>

                      <button

                          type="button"

                          class="btn-close"

                          data-bs-dismiss="modal"

                          aria-label="Close"

                      ></button>

                    </div>

                    <div class="modal-body">

                      <div class="mb-2">

                        <label for="bot-title" class="form-label"

                        >Bot Title</label

                        >

                        <input

                            v-model="bot.title"

                            type="text"

                            class="form-control"

                            id="bot-title"

                            placeholder="名称"

                        />

                      </div>

                      <div class="mb-2">

                        <label for="description" class="form-label"

                        >Description</label

                        >

                        <textarea

                            v-model="bot.description"

                            class="form-control"

                            id="description"

                            placeholder="简介"

                            rows="2"

                        ></textarea>

                      </div>

                      <div class="row">

                        <div class="mb-2 col-6">

                          <label for="language" class="form-label"

                          >Language</label

                          >

                          <select

                              v-model="bot.language"

                              class="form-select"

                              aria-label="Default select example"

                          >

                            <option>cpp</option>

                            <option>java</option>

                            <option>python3</option>

                            <option>python</option>

                          </select>

                        </div>

                        <div class="mb-2 col-6">

                          <label for="game" class="form-label">Game</label>

                          <select

                              v-model="bot.game"

                              class="form-select"

                              aria-label="Default select example"

                          >

                            <option>snake</option>

                            <option>reversi</option>

                          </select>

                        </div>

                      </div>

                      <div class="mb-2">

                        <label for="code" class="form-label">Code</label>

                        <a

                            class="code-template"

                            target="_blank"

                            href="https://www.yuque.com/docs/share/679878f3-95f6-4827-b41f-513852ac97a0?#%20%E3%80%8ABot%E4%BB%A3%E7%A0%81%E6%A8%A1%E6%9D%BF%E3%80%8B"

                        >代码模板</a

                        >

                        <VAceEditor

                            @init="editorInit"

                            v-model:value="bot.content"

                            :options="{

                              fontSize: 16,

                              enableBasicAutocompletion: true,

                              enableSnippets: true,

                              enableLiveAutocompletion: true,

                              showPrintMargin: false,

                              highlightActiveLine: true,

                            }"

                            lang="c_cpp"

                            theme="textmate"

                            style="height: 235px"

                        />

                      </div>

                    </div>

                    <div class="modal-footer">

                      <div class="error-msg">{{ error_msg }}</div>

                      <button

                          type="button"

                          class="btn btn-secondary"

                          data-bs-dismiss="modal"

                      >

                        取消

                      </button>

                      <button

                          type="button"

                          class="btn btn-primary"

                          @click="update_bot_event(bot)"

                      >

                        提交

                      </button>

                    </div>

                  </div>

                </div>

              </div>

            </td>

          </tr>

          </tbody>

        </table>

      </div>

    </div>

  </div>

</template>



import { ref, reactive } from 'vue'

import $ from 'jquery'

import { useStore } from 'vuex'

import { Modal } from 'bootstrap/dist/js/bootstrap'

import { VAceEditor } from 'vue3-ace-editor'

import 'ace-builds/src-noconflict/mode-c_cpp'

import 'ace-builds/src-noconflict/theme-textmate'

import 'ace-builds/src-noconflict/ext-language_tools'

import 'ace-builds/src-noconflict/snippets/c_cpp';

import 'ace-builds/src-noconflict/snippets/java';

import 'ace-builds/src-noconflict/snippets/python';

export default {

  name: "UserBotIndexView",

  components: {

    VAceEditor

  },

  setup () {

    let remove_bot_id = ref("");

    let bots = ref([]);

    let error_msg = ref("");

    const bot_add = reactive({

      title: "",

      description: "",

      language: "cpp",

      content: "",

      game: "snake",

    });

    const store = useStore();

    const refresh_bots = () => {

      $.ajax({

        url: "http://localhost:3000/user/bot/getlist/",

        type: "get",

        headers: {

          Authorization: "Bearer " + store.state.user.token,

        },

        success(resp) {

          if (resp && Array.isArray(resp)) {

            bots.value = resp;

          } else {

            console.error("Unexpected response format:", resp);

          }

        },

        error(resp) {

          console.error("Failed to fetch bots:", resp);

        }

      });

    };

    const add_bot_event = () => {

      error_msg.value = '';

      $.ajax({

        url: "http://localhost:3000/user/bot/add/",

        type: "post",

        data: {

          title: bot_add.title,

          description: bot_add.description,

          content: bot_add.content,

          game: bot_add.game,

          language: bot_add.language

        },

        headers: {

          Authorization: "Bearer " + store.state.user.token,

        },

        success(resp) {

          if (resp.error_message === "success") {

            bot_add.title = "";

            bot_add.description = "";

            bot_add.content = "";

            bot_add.game = "";

            bot_add.language = "";

            Modal.getInstance("#add-bot-button").hide();

            store.commit("updateBotCount", store.state.user.botCount + 1);

            refresh_bots();

          } else {

            error_msg.value = resp.error_message;

            setTimeout(() => {

              error_msg.value = '';

            }, 4000);

          }

        },

        error(resp) {

          error_msg.value = resp.responseJSON.error_message || "Failed to add bot";

          setTimeout(() => {

            error_msg.value = '';

          }, 4000);

        }

      });

    };

    const update_bot_event = (bot) => {

      error_msg.value = '';

      $.ajax({

        url: "http://localhost:3000/user/bot/update/",

        type: "post",

        data: {

          botId: bot.id,

          title: bot.title,

          description: bot.description,

          content: bot.content,

          game: bot.game,

          language: bot.language

        },

        headers: {

          Authorization: "Bearer " + store.state.user.token,

        },

        success(resp) {

          if (resp.error_message === "success") {

            Modal.getInstance("#update-bot-modal-" + bot.id).hide();

            refresh_bots();

          } else {

            error_msg.value = resp.error_message;

            setTimeout(() => {

              error_msg.value = '';

            }, 4000);

          }

        },

        error(resp) {

          error_msg.value = resp.responseJSON.error_message || "更新失败";

          setTimeout(() => {

            error_msg.value = '';

          }, 4000);

        }

      });

    };

    const confirm_bot_id = (id) => {

      remove_bot_id.value = id;

    }

    const remove_bot_event = () => {

      $.ajax({

        url: "http://localhost:3000/user/bot/remove/",

        type: "post",

        data: {

          botId: remove_bot_id.value,

        },

        headers: {

          Authorization: "Bearer " + store.state.user.token,

        },

        success (resp) {

          if (resp.error_message === "success") {

            Modal.getInstance('#delete_bot').hide();

            store.commit("updateBotCount", store.state.user.botCount - 1);

            refresh_bots();

          } else {

            alert(resp.error_message);

          }

        },

        error () {

          alert("Failed to delete bot");

        }

      });

    };

    refresh_bots();

    return {

      bots,

      bot_add,

      error_msg,

      add_bot_event,

      update_bot_event,

      remove_bot_event,

      confirm_bot_id,

    }

  }

}





.card-header-name {

  font-weight: bold;

  font-size: 24px;

  margin: 0 auto;

}

.error-msg {

  margin-right: 20px;

  font-size: 16px;

  color: #c3404b;

  font-family: Verdana, Geneva, Tahoma, sans-serif;

}

.add-bot {

  width: 60px;

  border: 1px;

  border-radius: 5px;

  background-color: #409eff;

  margin-top: 5px;

  outline: none;

}

.update-bot {

  width: 60px;

  border: 1px;

  border-radius: 5px;

  background-color: #b7c5d2;

  outline: none;

}

.remove-bot {

  margin-left: 10px;

  width: 60px;

  border: 1px;

  border-radius: 5px;

  background-color: #dd3545;

  outline: none;

}

button > span {

  font-size: 16px;

  color: rgb(23, 18, 18);

}

button:hover {

  scale: 1.1;

}

.bot-tr:hover {

  background-color: #d7d9da;

}

.bot-th {

  font-family: Cambria, Cochin, Georgia, Times, "Times New Roman", serif;

}

.code-template {

  float: right;

  font-weight: bold;

  text-decoration: none;

  color: rgb(132, 183, 200);

}

.text-left {

  text-align: left;

}


后端表结构有修改 对应接口需要改变


项目分区导航WebSocket实战篇 ⬅️ | 06-bot界面 增删改查 | ➡️ bot代码执行 排行榜页面