评论接口和数据库设计
comment 表设计
为了方便添加点赞,父评论和子评论都是顶级 document,可以通过_id 迅速定位。 并给 pageId 添加索引,方便一次查询出一篇文章的所有评论。
type comment = {_id: ObjectId,pageId: string,parentId: ObjectId, // 父评论id, 默认为nullcreateTime: number,clientTime: number,user: string,content: string,favor: number // 点赞数}
接口设计
一个路径/api/comment
;三种方法GET
、PUT
、POST
;三个功能:查询、添加、点赞;
查询评论
请求
使用 GET 方法,有两个 URL 参数
- pageId
- createTime createTime 是可选的,如果存在,只查询创建时间大于 createTime 的留言
{ "pageId": "posts/isaiah", "createTime": 1629415868485}
响应
{ "lastUpdateTime": 1629358376721, "comments": [ { "_id": "611e746968ba7ff4ec096969", "createTime": 1629358376721, "user": "摩西", "content": "咿呀,我来抢沙发", "favor": 0, "subComments": [] }, { "_id": "611e74ac68ba7ff4ec09696a", "createTime": 1629358376721, "user": "Bob", "content": "上帝有测不透的怜悯", "favor": 5, "subComments": [ { "_id": "611e751c68ba7ff4ec09696c", "createTime": 1629386012384, "user": "所罗门", "content": "一切都是虚空,一切都是捕风。", "clientTime": 1629331685895, "favor": 2 }, { "_id": "612259b98637b2b26f1ee8e9", "createTime": 1629641145698, "user": "wayne", "content": "耶和华你是我的牧者", "clientTime": 1629641145267, "favor": 10 } ] } ]}
添加评论
请求
使用 PUT 方法, 请求 Body 为 json 格式。5 个字段都是必须的,parentId
为 null 表示顶级评论
{ "pageId": "posts/isaiah", "parentId": "612259b98637b2b26f1ee8e9", "user": "巴拿马", "content": "敬畏耶和华是知识的开端; 愚妄人藐视智慧和训诲。", "clientTime": 1629722714646}
响应
返回服务端收到请求的时间
{ "createTime": 1629331683295 }
评论点赞
请求
使用 Post 方法, 请求 Body 为 json 格式。三个字段:
- action
- commentId
action 字段是为以后扩展 api 做准备,对于点赞, action 的值永远是 addFavor。点赞后,客户端可立即将点赞数加 1。等到服务端返回总点赞数之后再较正。
{ "action": "addFavor", "commentId": "612259b98637b2b26f1ee8e9"}
响应
返回当前评论总点赞数
{ "favor": 100 }

