携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第13天,点击查看活动详情
文章系列:
接着上篇文章的 标签管理 编写
这篇文章编写 标签管理的接口
1.首先 编写 关注 标签的逻辑,新建 pages/api/tag/follow.ts
2.首先引入数据库配置
import { NextApiRequest, NextApiResponse } from 'next';
import { withIronSessionApiRoute } from 'iron-session/next';
import { ironOptions } from 'config/index';
import { ISession } from 'pages/api/index';
import { prepareConnection } from 'db/index';
import { Tag, User } from 'db/entity/index';
import { EXCEPTION_USER, EXCEPTION_TAG } from 'pages/api/config/codes';
export default withIronSessionApiRoute(follow, ironOptions);
3.从session获取用户的id
const session: ISession = req.session;
const { userId = 0 } = session;
4.从 body中获取 前端传过来的参数,一共两个参数,一个type,值分别是follow和unfollow,表示是取消关注还是关注,另外一个参数数标签的id
const { tagId, type } = req?.body || {};
5.链接 标签和用户的数据库
const db = await prepareConnection();
const tagRepo = db.getRepository(Tag);
const userRepo = db.getRepository(User);
6.根据用户id去用户表中查询该用户信息,如果没找到,则提示当前用户不存在
const user = await userRepo.findOne({
where: {
id: userId,
},
});
if (!user) {
res?.status(200).json({
...EXCEPTION_USER?.NOT_LOGIN,
});
return;
}
7.根据标签id从标签的数据表中查询所有标签
const tag = await tagRepo.findOne({
relations: ['users'],
where: {
id: tagId,
},
});
8.如果从标签表中查询出有用户,如果类型是follow,则表示是关注操作,则将当前用户添加到 关注该标签的用户数据中,并且将关注该标签的数据增加1,如果类型是unfollow,则表示取消关注操作,则将当前用户从 关注该标签的用户数据中剔除,并且将关注该标签的数据减1.
if (tag?.users) {
if (type === 'follow') {
tag.users = tag?.users?.concat([user]);
tag.follow_count = tag?.follow_count + 1;
} else if (type === 'unfollow') {
tag.users = tag?.users?.filter((user) => user.id !== userId);
tag.follow_count = tag?.follow_count - 1;
}
}
9.最后将 标签的数据存入 标签的数据表中,如果成功,则返回200,否则提示失败
if (tag) {
const resTag = await tagRepo?.save(tag);
res?.status(200)?.json({
code: 0,
msg: '',
data: resTag,
});
} else {
res?.status(200)?.json({
...EXCEPTION_TAG?.FOLLOW_FAILED,
});
}
10.在前端点击关注的时候,传入两个参数,一个参数是type,值为follw,另外一个参数是标签id,如果接口成功,在前端提示关注成功,并且重新调标签的数据,刷新页面
request.post('/api/tag/follow', {
type: 'follow',
tagId
}).then((res: any) => {
if (res?.code === 0) {
message.success('关注成功');
setNeedRefresh(!needRefresh);
} else {
message.error(res?.msg || '关注失败');
}
})
11.取消关注,则是将type参数的值改成 unfollow。
const handleUnFollow = (tagId: number) => {
request.post('/api/tag/follow', {
type: 'unfollow',
tagId
}).then((res: any) => {
if (res?.code === 0) {
message.success('取关成功');
setNeedRefresh(!needRefresh);
} else {
message.error(res?.msg || '取关失败');
}
})
}