익명 커뮤니티 게시판을 만들고싶었다.
익명 기능은 에브리타임 기능처럼 익명1, 익명2, 익명3 식으로 댓글 작성자의 id를 익명으로 가리고 해당 게시물에 댓글을 단 순서대로 1, 2, 3 인덱스를 붙혀주는 기능으로 구현을 하고싶었다.
처음엔 아주 단순해보였지만 개발하다보니 신경을 써야 할 부분이 많았다.
1. 작성자의 id를 익명으로 가림
-> 단순하게 익명 테이블만 작성자 id를 저장하는 방식을 바꾸면 됨
2. 댓글을 단 순서대로 인덱싱
-> 게시글 테이블에 인덱스 관련 컬럼을 추가 후 댓글이 달릴 때마다 컬럼의 값을 1씩 상승
3. 댓글 단 사람의 인덱싱을 기억
-> 이게 가장 까다로웠다.
일단 기본적으로 작성자의 id를 익명으로 가려야 하지만 인덱싱을 기억하기 위해선 작성자의 정보를 가지고 있어야한다.
// 익명 순번을 위한
let anonymousIndexMap = {};
// 게시판마다 익명 순번을 초기화하는 함수
function initializeAnonymousIndex(boardId) {
anonymousIndexMap[boardId] = {};
}
// 댓글 작성
router.post('/write', async (req, res) => {
try {
const postId = req.body.postId;
if (!anonymousIndexMap.hasOwnProperty(postId)) {
initializeAnonymousIndex(postId);
}
const writer = req.body.writer;
let anonymousIndex;
// 만약 전에 댓글을 작성했으면 동일한 index
if (anonymousIndexMap.hasOwnProperty(writer)) { // hasOwnProperty -> 객체가 특정 값 가지고있는지 확인
anonymousIndex = anonymousIndexMap[writer];
} else {
anonymousIndex = Object.keys(anonymousIndexMap).length; // 새로운 writer의 경우, 새로운 익명 Index 부여
anonymousIndexMap[writer] = anonymousIndex; // writer와 익명 Index를 매핑
}
let obj;
obj = {
postId: req.body.postid,
writer: req.body.writer,
content: req.body.content,
anonymousIndex: anonymousIndex,
};
const anonyComment = new AnonyComment(obj);
await AnonyComment.insertMany(anonyComment);
await Member.updateOne(
{ id: req.body.id },
{
$inc: { // $inc: 기존 필드값을 +/- 연산을 할 수 있음
point: 1 // 일단 글쓸때마다 1포인트로 지정
}
});
res.json({ message: true });
} catch (err) {
console.log(err);
res.json({ message: false });
}
});
// 대댓글 작성
router.post('/reWrite', async (req, res) => {
try {
const writer = req.body.writer;
let anonymousIndex;
// 만약 전에 댓글을 작성했으면 동일한 index
if (anonymousIndexMap.hasOwnProperty(writer)) {
anonymousIndex = anonymousIndexMap[writer];
} else {
anonymousIndex = Object.keys(anonymousIndexMap).length;
anonymousIndexMap[writer] = anonymousIndex;
}
let obj;
obj = {
writer: req.body.writer,
content: req.body.content,
createdAt: req.body.createdAt,
anonymousIndex: anonymousIndex
};
await AnonyComment.findOneAndUpdate(
{ _id: req.body.commentId },
{
$push: {
reComment: obj
}
}
)
await Member.updateOne(
{ id: req.body.id },
{
$inc: { // $inc: 기존 필드값을 +/- 연산을 할 수 있음
point: 1 // 일단 글쓸때마다 1포인트로 지정
}
});
res.json({ message: true });
} catch (err) {
console.log(err);
res.json({ message: false })
}
})
익명 순번을 위한 indexmap을 상단에 초기화 시켜둔다.
글 마다 관리되어야 하기 때문에 인덱스를 초기화 하는 함수도 만들고
댓글 작성 엔드포인트가 들어왔을때 바로 실행시켜준다.
해당 방식을 통해 원하는 기능을 완벽히 구현했다.
하지만 보안이나 암호화에 대해 신경을 쓰지 못했을 때라 해당 방식으로 구현 할 경우 페이지에 노출되는 정보는 익명이지만 DB 테이블에는 작성자의 정보를 그대로 담고있어 완벽한 익명을 보장할 수 없다.
이부분은 SHA256같은 암호화를 통해 작성자 id를 암호화 시키는 방식으로 개선 가능하다.
'프로젝트 코드리뷰 > ITTY' 카테고리의 다른 글
게시글 조회 (+댓글 +대댓글) 랜더링 속도 개선 (0) | 2024.02.13 |
---|---|
FireBase 이미지 호스팅 (React, Quill) (0) | 2023.11.21 |
리액트 스와이프(드래그 스크롤) 기능구현 (0) | 2023.11.21 |