夜猫子的知识栈 夜猫子的知识栈
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

夜猫子

前端练习生
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • Node基础

  • 《MySQL》学习笔记

  • Midway

  • Nest

    • 开篇词
    • 学习理由
    • nest概念扫盲
    • 快速掌握 nestcli
    • 5种http数据传输方式
    • IoC 解决了什么痛点问题?
    • 如何调试 Nest 项目
    • Provider注入对象
    • 全局模块和生命周期
    • AOP 架构有什么好处?
    • 一网打尽 Nest 全部装饰器
    • Nest如何自定义装饰器
    • Metadata和Reflector
    • ExecutionContext切换上下文
    • Module和Provider的循环依赖处理
    • 如何创建动态模块
    • Nest和Express,fastify
    • Nest的Middleware
    • RxJS和Interceptor
    • 内置Pipe和自定义Pipe
    • ValidationPipe验证post请求参数
    • 如何自定义 Exception Filter
    • 图解串一串 Nest 核心概念
    • 接口如何实现多版本共存
    • Express如何使用multer实现文件上传
    • Nest使用multer实现文件上传
    • 图书管理系统
    • 大文件分片上传
    • 最完美的 OSS 上传方案
    • Nest里如何打印日志
    • 为什么Node里要用Winston打印日志
    • Nest 集成日志框架 Winston
    • 通过Desktop学Docker也太简单了
    • 你的第一个 Dockerfile
    • Nest 项目如何编写 Dockerfile
    • 提升 Dockerfile 水平的 5 个技巧
    • Docker 是怎么实现的
    • 为什么 Node 应用要用 PM2 来跑?
    • 快速入门 MySQL
    • SQL 查询语句的所有语法和函数
    • 一对一、join 查询、级联方式
    • 一对多、多对多关系的表设计
    • 子查询和 EXISTS
    • SQL 综合练习
    • MySQL 的事务和隔离级别
    • MySQL 的视图、存储过程和函数
    • Node 操作 MySQL 的两种方式
    • 快速掌握 TypeORM
    • TypeORM 一对一的映射和关联 CRUD
    • TypeORM 一对多的映射和关联 CRUD
    • TypeORM 多对多的映射和关联 CRUD
    • 在 Nest 里集成 TypeORM
    • TypeORM保存任意层级的关系
    • 生产环境为什么用TypeORM的migration迁移功能
    • Nest 项目里如何使用 TypeORM 迁移
    • 如何动态读取不同环境的配置?
    • 快速入门 Redis
    • 在 Nest 里操作 Redis
    • 为什么不用 cache-manager 操作 Redis
    • 两种登录状态保存方式:JWT、Session
    • Nest 里实现 Session 和 JWT
    • MySQL + TypeORM + JWT 实现登录注册
    • 基于 ACL 实现权限控制
    • 基于 RBAC 实现权限控制
    • access_token和refresh_token实现无感登录
    • 单token无限续期实现登录无感刷新
    • 使用 passport 做身份认证
    • passport 实现 GitHub 三方账号登录
    • passport 实现 Google 三方账号登录
    • 为什么要使用 Docker Compose ?
    • Docker 容器通信的最简单方式:桥接网络
    • Docker 支持重启策略,是否还需要 PM2
    • 快速掌握 Nginx 的 2 大核心用法
    • 基于 Nginx 实现灰度系统
    • 基于 Redis 实现分布式 session
    • Redis + 高德地图,实现附近的充电宝
    • 用 Swagger 自动生成 api 文档
    • 如何灵活创建 DTO
    • class- validator 的内置装饰器,如何自定义装饰器
    • 序列化 Entity,你不需要 VO 对象
    • 手写序列化 Entity 的拦截器
    • 使用 compodoc 生成文档
    • Node 如何发邮件?
    • 实现基于邮箱验证码的登录
    • 基于 sharp 实现 gif 压缩工具
    • 大文件如何实现流式下载?
    • Puppeteer 实现爬虫,爬取 BOSS 直聘全部前端岗位
    • 实现扫二维码登录
    • Nest 的 REPL 模式
    • 实现 Excel 导入导出
    • 如何用代码动态生成 PPT
    • 如何拿到服务器 CPU、内存、磁盘状态
    • Nest 如何实现国际化?
    • 会议室预订系统:需求分析和原型图
    • 会议室预订系统:技术方案和数据库设计
    • 会议室预订系统:用户管理模块--用户注册
    • 会议室预订系统:用户管理模块--配置抽离、登录认证鉴权
    • 会议室预订系统:用户管理模块-- interceptor、修改信息接口
    • 会议室预订系统:用户管理模块--用户列表和分页查询
    • 会议室预订系统:用户管理模块-- swagger 接口文档
    • 会议室预订系统:用户管理模块-- 用户端登录注册页面
    • 会议室预订系统:用户管理模块-- 用户端信息修改页面
    • 会议室预订系统:用户管理模块-- 头像上传
    • 会议室预订系统:用户管理模块-- 管理端用户列表页面
    • 会议室预订系统:用户管理模块-- 管理端信息修改页面
    • 会议室预订系统:会议室管理模块-后端开发
    • 会议室预订系统:会议室管理模块-管理端前端开发
    • 会议室预订系统:会议室管理模块-用户端前端开发
    • 会议室预订系统:预定管理模块-后端开发
    • 会议室预订系统:预定管理模块-管理端前端开发
    • 会议室预订系统:预定管理模块-用户端前端开发
    • 会议室预订系统:统计管理模块-后端开发
    • 会议室预订系统:统计管理模块-前端开发
    • 会议室预订系统:后端项目部署到阿里云
    • 会议室预订系统:前端项目部署到阿里云
    • 会议室预定系统:用 migration 初始化表和数据
    • 会议室预定系统:文件上传 OSS
    • 会议室预定系统:Google 账号登录后端开发
    • 会议室预定系统:Google 账号登录前端开发
    • 会议室预定系统:后端代码优化
    • 会议室预定系统:集成日志框架 winston
    • 会议室预定系统:前端代码优化
    • 会议室预定系统:全部功能测试
    • 会议室预定系统:项目总结
    • Nest 如何创建微服务?
    • Nest 的 Monorepo 和 Library
    • 用 Etcd 实现微服务配置中心和注册中心
    • Nest 集成 Etcd 做注册中心、配置中心
    • 用 Nacos 实现微服务配置中心和注册中心
    • 基于 gRPC 实现跨语言的微服务通信
    • 快速入门 ORM 框架 Prisma
    • Prisma 的全部命令
    • Prisma 的全部 schema 语法
    • Primsa Client 单表 CRUD 的全部 api
    • Prisma Client 多表 CRUD 的全部 api
    • 在 Nest 里集成 Prisma
    • 为什么前端监控系统要用 RabbitMQ?
    • 基于 Redis 实现关注关系
    • 基于 Redis 实现各种排行榜(周榜、月榜、年榜)
    • 考试系统:需求分析
    • 考试系统:技术方案和数据库设计
    • 考试系统:微服务、Lib 拆分
    • 考试系统;用户注册
    • 考试系统:用户登录、修改密码
    • 考试系统:考试微服务
    • 考试系统:登录、注册页面
    • 考试系统:修改密码、试卷列表页面
    • 考试系统:新增试卷、回收站
    • 考试系统:试卷编辑器
    • 考试系统:试卷回显、预览、保存
    • 考试系统:答卷微服务
    • 考试系统:答题页面
    • 考试系统:自动判卷
    • 考试系统:分析微服务、排行榜页面
    • 考试系统:整体测试
    • 考试系统:项目总结
    • 用 Node.js 手写 WebSocket 协议
    • Nest 开发 WebSocket 服务
    • 基于 Socket.io 的 room 实现群聊
    • 聊天室:需求分析和原型图
    • 聊天室:技术选型和数据库设计
    • 聊天室:用户注册
    • 聊天室:用户登录
    • 聊天室:修改密码、修改信息
    • 聊天室:好友列表、发送好友申请
    • 聊天室:创建聊天室、加入群聊
    • 聊天室:登录、注册页面开发
    • 聊天室:修改密码、信息页面开发
    • 聊天室:头像上传
    • 聊天室:好友∕群聊列表页面
    • 聊天室:添加好友弹窗、通知页面
      • 总结
    • 聊天室:聊天功能后端开发
    • 聊天室:聊天功能前端开发
    • 聊天室:一对一聊天
    • 聊天室:创建群聊、进入群聊
    • 聊天室:发送表情、图片、文件
    • 聊天室:收藏
    • 聊天室:全部功能测试
    • 聊天室:项目总结
    • MongoDB 快速入门
    • 使用 mongoose 操作 MongoDB 数据库
    • GraphQL 快速入门
    • Nest 开发 GraphQL 服务:实现 CRUD
    • GraphQL + Primsa + React 实现 TodoList
    • 如何调试 Nest 源码?
  • 其他

  • 服务端
  • Nest
神说要有光
2025-03-10
目录

聊天室:添加好友弹窗、通知页面

上节实现了好友、群聊的列表,这节来实现添加好友功能

添加 src/pages/Friendship/AddFriendModal.tsx

import { Button, Form, Input, InputNumber, Modal, message } from "antd";
import { useForm } from "antd/es/form/Form";
import TextArea from "antd/es/input/TextArea";
import { useState } from "react";

interface AddFriendModalProps {
    isOpen: boolean;
    handleClose: Function
}

const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 }
}

export interface AddFriend {
    username: string;
    reason: string;
}

export function AddFriendModal(props: AddFriendModalProps) {

    const [form] = useForm<AddFriend>();

    const handleOk = async function() {

    }

    return <Modal 
        title="添加好友"
        open={props.isOpen}
        onOk={handleOk}
        onCancel={() => props.handleClose()}
        okText={'发送好友请求'}
        cancelText={'取消'}    
    >
        <Form
            form={form}
            colon={false}
            {...layout}
        >
            <Form.Item
                label="用户名"
                name="username"
                rules={[
                    { required: true, message: '请输入用户名!' },
                ]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="添加理由"
                name="reason"
                rules={[
                    { required: true, message: '请输入添加理由!' },
                ]}
            >
                <TextArea />
            </Form.Item>
        </Form>
    </Modal>
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

然后在 Friednship/index.tsx 里引入下:

添加一个 state 控制弹窗显示隐藏,然后加一个按钮,点击的时候设置 state 为 true,关闭弹窗的时候设置 state 为 false

const [isAddFriendModalOpen, setAddFriendModalOpen] = useState(false);
1
<Form.Item label=" ">
    <Button type="primary" style={{background: 'green'}} onClick={() => setAddFriendModalOpen(true)}>
        添加好友
    </Button>
</Form.Item>
1
2
3
4
5
<AddFriendModal isOpen={isAddFriendModalOpen} handleClose={() => {
    setAddFriendModalOpen(false)
}}/>
1
2
3

测试下:

然后调用下添加好友的接口。

之前是通过 id 来添加的好友:

现在要改一下:

import { IsNotEmpty } from "class-validator";

export class FriendAddDto {

    @IsNotEmpty({
        message: "添加好友的 username 不能为空"
    })
    username: string;

    reason: string;    
}
1
2
3
4
5
6
7
8
9
10
11

然后改下 service 的实现:

async add(friendAddDto: FriendAddDto, userId: number) {
    const friend = await this.prismaService.user.findUnique({
        where: {
            username: friendAddDto.username
        }
    });

    if(!friend) {
        throw new BadRequestException('要添加的 username 不存在');
    }

    if(friend.id === userId) {
        throw new BadRequestException('不能添加自己为好友');
    }

    const found = await this.prismaService.friendship.findMany({
        where: {
            userId,
            friendId: friend.id
        }
    })

    if(found.length) {
        throw new BadRequestException('该好友已经添加过');
    }

    return await this.prismaService.friendRequest.create({
        data: {
            fromUserId: userId,
            toUserId: friend.id,
            reason: friendAddDto.reason,
            status: 0
        }
    })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

先根据 username 查询 user,如果不存在就返回错误,提示 username 不存在。

如果添加的是自己,返回错误,提示不能添加自己为好友。

如果已经添加过,返回错误,提示已经添加。

否则,创建好友申请。

在页面调用下:

interfaces 加一下这个接口

export async function friendAdd(data: AddFriend) {
    return axiosInstance.post('/friendship/add', data);
}
1
2
3

组件里调用下:

const handleOk = async function() {
    await form.validateFields();

    const values = form.getFieldsValue();

    try{
        const res = await friendAdd(values);

        if(res.status === 201 || res.status === 200) {
            message.success('好友申请已发送');
            form.resetFields();
            props.handleClose();
        }
    } catch(e: any){
        message.error(e.response?.data?.message || '系统繁忙,请稍后再试');
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

试下效果:

提示好友申请已发送。

其中 hong 提示已经是好友了,我们查一下:

/friendship/list

确实。

然后查一下新的好友请求:

已经有了。

然后我们写一下通知页面:

之前的好友请求列表接口有点问题:

其实用户发出的好友请求、发给用户的好友请求,都应该展示出来。

并且接口应该顺带把用户信息也给查出来返回。

我们完善下:

async list(userId: number) {
    const fromMeRequest = await this.prismaService.friendRequest.findMany({
        where: {
            fromUserId: userId
        }
    })

    const toMeRequest =  await this.prismaService.friendRequest.findMany({
        where: {
            toUserId: userId
        }
    })

    const res = {
        toMe: [],
        fromMe: []
    }

    for (let i = 0; i < fromMeRequest.length; i++) {
        const user = await this.prismaService.user.findUnique({
            where: {
                id: fromMeRequest[i].toUserId
            },
            select: {
                id: true,
                username: true,
                nickName: true,
                email: true,
                headPic: true,
                createTime: true
            }
        })
        res.fromMe.push({
            ...fromMeRequest[i],
            toUser: user
        })
    }

    for (let i = 0; i < toMeRequest.length; i++) {
        const user = await this.prismaService.user.findUnique({
            where: {
                id: toMeRequest[i].fromUserId
            },
            select: {
                id: true,
                username: true,
                nickName: true,
                email: true,
                headPic: true,
                createTime: true
            }
        })
        res.toMe.push({
            ...toMeRequest[i],
            fromUser: user
        })
    }

    return res;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

分别查询 fromUserId、toUsrId 为 userId 的好友请求,然后把其中的 user 查出来返回。

测试下:

因为现在还没有发送给当前用户的好友请求。

我们在界面发送一个:

再查询就有了:

然后我们在页面把这个显示下就行:

src/pages/Notification.tsx

import { Button, Form, Input, Popconfirm, Table, Tabs, TabsProps, message } from "antd";
import { useForm } from "antd/es/form/Form";
import './index.css';

export function Notification() {

    const [form ]  = useForm();

    const onChange = (key: string) => {
        console.log(key);
    };
      
    const items: TabsProps['items'] = [
        {
          key: '1',
          label: '我发出的',
          children: '发给我的',
        },
        {
          key: '2',
          label: '我发出的',
          children: '我发出的',
        }
    ];

    return <div id="notification-container">
        <div className="notification-list">
            <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
        </div>
    </div>
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

css

#notification-container {
    padding: 20px;
}
1
2
3

然后在 interfaces 添加下接口:

export async function friendRequestList() {
    return axiosInstance.get('/friendship/request_list');
}
1
2
3

在页面调用下:

import { Button, Form, Input, Popconfirm, Table, Tabs, TabsProps, message } from "antd";
import { useForm } from "antd/es/form/Form";
import './index.css';
import { useEffect, useState } from "react";
import { friendRequestList } from "../../interfaces";

interface User {
    id: number;
    headPic: string;
    nickName: string;
    email: string;
    captcha: string;
}

interface FriendRequest {
    id: number
    fromUserId: number
    toUserId: number
    reason: string
    createTime: Date
    fromUser: User
    toUser: User
    status: number
}

export function Notification() {

    const [form ]  = useForm();
    const [fromMe, setFromMe] = useState<Array<FriendRequest>>([]);
    const [toMe, setToMe] = useState<Array<FriendRequest>>([]);

    async function queryFriendRequestList() {
        try{
            const res = await friendRequestList();

            if(res.status === 201 || res.status === 200) {
                setFromMe(res.data.fromMe.map((item: FriendRequest) => {
                    return {
                        ...item,
                        key: item.id
                    }
                }));
                setToMe(res.data.toMe.map((item: FriendRequest) => {
                    return {
                        ...item,
                        key: item.id
                    }
                }));
            }
        } catch(e: any){
            message.error(e.response?.data?.message || '系统繁忙,请稍后再试');
        }
    }

    useEffect(() => {
        queryFriendRequestList();
    }, []);

    const onChange = (key: string) => {
        console.log(key);
    };
      
    const items: TabsProps['items'] = [
        {
            key: '1',
            label: '我发出的',
            children: <div style={{width: 1000}}>
                {JSON.stringify(fromMe)}
            </div>
        },
        {
            key: '2',
            label: '发给我的',
            children: <div style={{width: 1000}}>
                {JSON.stringify(toMe)}
            </div>
        }
    ];

    return <div id="notification-container">
        <div className="notification-list">
            <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
        </div>
    </div>
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

请求下接口,设置到 fromMe、toMe 的 state:

然后在 tab 内容展示下:

看下效果:

数据请求成功。

我们用 table 展示下就好了:

import { Button, Form, Input, Popconfirm, Table, Tabs, TabsProps, message } from "antd";
import { useForm } from "antd/es/form/Form";
import './index.css';
import { useEffect, useMemo, useState } from "react";
import { friendRequestList } from "../../interfaces";
import { ColumnsType } from "antd/es/table";

interface User {
    id: number;
    headPic: string;
    nickName: string;
    email: string;
    captcha: string;
}

interface FriendRequest {
    id: number
    fromUserId: number
    toUserId: number
    reason: string
    createTime: Date
    fromUser: User
    toUser: User
    status: number
}

export function Notification() {

    const [form ]  = useForm();
    const [fromMe, setFromMe] = useState<Array<FriendRequest>>([]);
    const [toMe, setToMe] = useState<Array<FriendRequest>>([]);

    async function queryFriendRequestList() {
        try{
            const res = await friendRequestList();

            if(res.status === 201 || res.status === 200) {
                setFromMe(res.data.fromMe.map((item: FriendRequest) => {
                    return {
                        ...item,
                        key: item.id
                    }
                }));
                setToMe(res.data.toMe.map((item: FriendRequest) => {
                    return {
                        ...item,
                        key: item.id
                    }
                }));
            }
        } catch(e: any){
            message.error(e.response?.data?.message || '系统繁忙,请稍后再试');
        }
    }

    useEffect(() => {
        queryFriendRequestList();
    }, []);

    const onChange = (key: string) => {
        console.log(key);
    };
      
    const toMeColumns: ColumnsType<FriendRequest> = [
        {
            title: '用户',
            render: (_, record) => {
                return <div>
                    <img src={record.fromUser.headPic} width={30} height={30}/>
                    {' ' + record.fromUser.nickName + ' 请求加你为好友'}
                </div>
            }
        },
        
        {
            title: '请求时间',
            render: (_, record) => {
                return new Date(record.createTime).toLocaleString()
            }
        },
        {
            title: '操作',
            render: (_, record) => (
                <div>
                    <a href="#">同意</a><br/>
                    <a href="#">拒绝</a>
                </div>
            )
        }
    ]

    const fromMeColumns: ColumnsType<FriendRequest> = [
        {
            title: '用户',
            render: (_, record) => {
                return <div>
                    {' 请求添加好友 ' + record.toUser.nickName}
                    <img src={record.toUser.headPic} width={30} height={30}/>
                </div>
            }
        },
        
        {
            title: '请求时间',
            render: (_, record) => {
                return new Date(record.createTime).toLocaleString()
            }
        },
        {
            title: '状态',
            render: (_, record) => {
                const map: Record<string, any> = {
                    0: '申请中',
                    1: '已通过',
                    2: '已拒绝'
                }
                return <div>
                    {map[record.status]}
                </div>
            }
        }
    ]

    const items: TabsProps['items'] = [
        {
            key: '1',
            label: '发给我的',
            children: <div style={{width: 1000}}>
                <Table columns={toMeColumns} dataSource={toMe} style={{width: '1000px'}}/>
            </div>
        },
        {
            key: '2',
            label: '我发出的',
            children: <div style={{width: 1000}}>
                <Table columns={fromMeColumns} dataSource={fromMe} style={{width: '1000px'}}/>
            </div>
        }
    ];

    return <div id="notification-container">
        <div className="notification-list">
            <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
        </div>
    </div>
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146

看下效果:

没啥问题。

然后加一下同意和拒绝的接口调用:

export async function agreeFriendRequest(id: number) {
    return axiosInstance.get(`/friendship/agree/${id}`);
}

export async function rejectFriendRequest(id: number) {
    return axiosInstance.get(`/friendship/reject/${id}`);
}
1
2
3
4
5
6
7

然后页面上调用下:

{
    title: '操作',
    render: (_, record) => {
        if(record.status === 0) {
            return <div>
                <a href="#" onClick={() => agree(record.fromUserId)}>同意</a><br/>
                <a href="#" onClick={() => reject(record.fromUserId)}>拒绝</a>
            </div>
        } else {
            const map: Record<string, any> = {
                1: '已通过',
                2: '已拒绝'
            }
            return <div>
                {map[record.status]}
            </div>
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
async function agree(id: number) {
    try{
        const res = await agreeFriendRequest(id);

        if(res.status === 201 || res.status === 200) {
            message.success('操作成功');
            queryFriendRequestList();
        }
    } catch(e: any){
        message.error(e.response?.data?.message || '系统繁忙,请稍后再试');
    }
}

async function reject(id: number) {
    try{
        const res = await rejectFriendRequest(id);

        if(res.status === 201 || res.status === 200) {
            message.success('操作成功');
            queryFriendRequestList();
        }
    } catch(e: any){
        message.error(e.response?.data?.message || '系统繁忙,请稍后再试');
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

试下效果:

同意后再看下好友列表:

多了小强这个好友。

我们好像忘记展示 reason 了,补一下:

最后,我们整体测试下添加好友的功能:

首先登录一个用户的账号,给 guang 发送好友请求:

然后登录 guang 的账号:

同意之后,就可以在好友列表看到这个好友了。

前端代码 (opens new window)

后端代码 (opens new window)

# 总结

这节我们实现了添加好友。

首先点击添加好友按钮的时候会有个弹窗,输入 username 和理由之后,会发送一个好友请求。

在通知页面分别展示发给我的和我发出的好友请求,对方点击同意后,就会成为好友了。

这样添加好友、好友请求的功能就完成了。

编辑 (opens new window)
上次更新: 2025/10/27 10:53:52
聊天室:好友∕群聊列表页面
聊天室:聊天功能后端开发

← 聊天室:好友∕群聊列表页面 聊天室:聊天功能后端开发→

最近更新
01
H5调用微信jssdk
09-28
02
VueVirtualScroller
09-19
03
如何调试 Nest 项目
03-10
更多文章>
Copyright © 2019-2025 Study | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式