npm init -y
npm i -D typescript nodemon ts-node
npx tsc --init
- 게시글 검색 기능 설계할 것
- 게시글 상세페이지 정보 설계 할 것
- 댓글에는 대댓글을 달 수 있도록 설계할 것
- 같은 User가 게시글을 읽는 경우 count 수 증가되지 않도록 설계할 것
- Restful API 규칙에 따라 설계할 것
const getBoardWithComment = async (
boardId: string,
commentOffset: string,
commentLimit: string
) => {
const start = (Number(commentOffset) - 1) * Number(commentLimit);
게시글 검색
GET /boards API 를 사용해서 검색가능합니다.또한 keyWord는 자유작성이 가능합니다. 게시글 제목, 카테고리, 본문, 작성자 ,댓글 을 포함한 데이터는 모두 검색의 결과로서 나타납니다.
아래는 검색 부분의 구현한 코드입니다.
const getBoards = async (
req: Request<{}, {}, {}, { keyword: string }>,
res: Response
) => {
try {
const { keyword } = req.query;
const boardSearchResult = await boardServices.getBoards(keyword);
return res.status(200).json(boardSearchResult);
} catch (error) {
if (error instanceof HttpError) {
return res
.status(error.statusCode || 500)
.json({ message: error.message });
}
}
};
export const searchFilter = keyword => {
const searchColumn = [
'board_title',
'nick_name',
'board_contents',
'commentComment',
];
const conditions = searchColumn.map(
column => `${column} LIKE '%${keyword}%'`
);
return `(${conditions.join(' OR ')})`;
};
export const createComment = async (boardId, userId, comment, parent_id) => {
let cdepth;
if (parent_id !== undefined) {
let pdepth =
await prismaClient.$queryRaw`SELECT cdepth FROM comment WHERE id=${parent_id}`;
cdepth = Number(pdepth[0].cdepth) + 1;
} else {
cdepth = 0;
}
const query = `
INSERT INTO comment (
board_id,
user_id,
comment
${parent_id ? `, parent_id, cdepth` : ``})
VALUES (
${boardId},
${userId},
"${comment}"
${parent_id ? `, ${parent_id}, ${cdepth}` : ``}
);
`;
await prismaClient.$queryRawUnsafe(query);
export const getUserById = async (boardId, userId) => {
const [existingUser] = await prismaClient.$queryRaw`
SELECT * FROM view WHERE board_id=${boardId} AND user_id= ${userId}
`;
return existingUser;
};
export const updateBoardViews = async (boardId, userId) => {
return await prismaClient.$queryRaw`
INSERT INTO view (board_id,user_id) VALUES(${boardId},${userId})
`;
};
js는 정적 타입을 지원하지 않으므로 타입의 반환값을 리턴해주어야 한다.
ts는 정적 타입을 지원, 컴파일 단계에서 오류 확인에 장점이 있다
타입을 지정해주기 때문에 컴파일 단계에서 타입체크를 하면서 오류,버그를 catch 가능
ts 컴파일러를 사용하여 js파일로 변환을 쉽게 할 수 있다.