Skip to content

Commit

Permalink
v1.1.7 (#25)
Browse files Browse the repository at this point in the history
Modify: findUserFeedsByUserId 함수
  - 게시물 검색시 postedAt: DESC 정렬
  - 임시저장물 검색시 updatedAt: DESC 정렬
  - 페이지네이션 적용
  - 페이지네이션이 없을 땐 전체 목록

Modify: findUserCommentsByUserId 함수
  - 덧글 검색시 createdAt: DESC 정렬
  - 무한스크롤 적용
  - 무한스크롤이 없을 땐 전체 목록

Modify: findUserFeedSymbolsByUserId 함수
  - 페이지네이션 적용

Modify: 사용자의 정보 가져오기 라우팅 경로 수정
  - params의 id값이 있다면 해당 id의 사용자 정보를 반환
  - params의 id값이 없다면 로그인한 사용자 정보를 반환

Fix: 사용자의 정보 가져오기
  - 라우팅 경로에서 parameter id의 값이 없고 로그인도 하지 않은 경우, 에러가 아닌 DB의 첫 결과값을 반환하던 문제 해결
  • Loading branch information
inchanS authored May 3, 2023
1 parent c21fdfc commit e2e3633
Show file tree
Hide file tree
Showing 8 changed files with 232 additions and 71 deletions.
83 changes: 75 additions & 8 deletions src/controllers/users.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Request, Response } from 'express';
import usersService from '../services/users.service';
import { UserDto } from '../entities/dto/user.dto';
import { Pagination } from '../repositories/feed.repository';

const checkDuplicateNickname = async (
req: Request,
Expand Down Expand Up @@ -37,16 +38,80 @@ const signIn = async (req: Request, res: Response): Promise<void> => {
res.status(200).json({ message: `SIGNIN_SUCCESS`, result });
};

const getMe = async (req: Request, res: Response): Promise<void> => {
const result = await usersService.getMe(req.userInfo.id);
// 유저의 가입정보 가져오기
const getUserInfo = async (req: Request, res: Response): Promise<void> => {
let targetUserId = Number(req.params.id);
const loggedInUserId = req.userInfo.id;

if (!targetUserId) {
targetUserId = loggedInUserId;
}
const result = await usersService.findUserInfoByUserId(targetUserId);

res.status(200).json(result);
};

// 다른 사람의 정보 가져오기
const getUserInfo = async (req: Request, res: Response): Promise<void> => {
const targetUserId = Number(req.params.id);
// 유저의 모든 게시물 가져오기
const getUserFeeds = async (req: Request, res: Response): Promise<void> => {
let targetUserId = Number(req.params.id);
const loggedInUserId = req.userInfo.id;

if (!targetUserId) {
targetUserId = loggedInUserId;
}

const startIndex = Number(req.query.page);
const limit = Number(req.query.limit);
const page: Pagination = { startIndex, limit };

const result = await usersService.findUserFeedsByUserId(targetUserId, page);

res.status(200).json(result);
};

// 유저의 모든 덧글 가져오기
const getUserComments = async (req: Request, res: Response): Promise<void> => {
let targetUserId = Number(req.params.id);
const loggedInUserId = req.userInfo.id;

if (!targetUserId) {
targetUserId = loggedInUserId;
}

const startIndex = Number(req.query.index);
const limit = Number(req.query.limit);
const page: Pagination = { startIndex, limit };

const result = await usersService.findUserCommentsByUserId(
targetUserId,
loggedInUserId,
page
);

res.status(200).json(result);
};

// 유저의 모든 좋아요 가져오기
const getUserFeedSymbols = async (
req: Request,
res: Response
): Promise<void> => {
let targetUserId = Number(req.params.id);
const loggedInUserId = req.userInfo.id;
const result = await usersService.getUserInfo(targetUserId, loggedInUserId);

if (!targetUserId) {
targetUserId = loggedInUserId;
}

const startIndex = Number(req.query.page);
const limit = Number(req.query.limit);
const page: Pagination = { startIndex, limit };

const result = await usersService.findUserFeedSymbolsByUserId(
targetUserId,
page
);

res.status(200).json(result);
};

Expand Down Expand Up @@ -76,11 +141,13 @@ const resetPassword = async (req: Request, res: Response): Promise<void> => {
export default {
signUp,
signIn,
getMe,
checkDuplicateNickname,
checkDuplicateEmail,
getUserInfo,
updateUserInfo,
deleteUser,
resetPassword,
getUserInfo,
getUserFeeds,
getUserComments,
getUserFeedSymbols,
};
13 changes: 12 additions & 1 deletion src/repositories/comment.repository.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import dataSource from './data-source';
import { Comment } from '../entities/comment.entity';
import { CommentDto } from '../entities/dto/comment.dto';
import { Pagination } from './feed.repository';

export const CommentRepository = dataSource.getRepository(Comment).extend({
async getCommentList(id: number) {
Expand Down Expand Up @@ -45,11 +46,21 @@ export const CommentRepository = dataSource.getRepository(Comment).extend({
});
},

async getCommentListByUserId(userId: number) {
async getCommentListByUserId(userId: number, page: Pagination) {
let pageCondition = {};
if (page) {
pageCondition = {
skip: page.startIndex,
take: page.limit,
};
}

return await this.find({
withDeleted: true,
loadRelationIds: true,
where: { user: { id: userId } },
order: { created_at: 'DESC' },
...pageCondition,
});
},
});
32 changes: 29 additions & 3 deletions src/repositories/feed.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ export type FeedListOptions = {
includeTempFeeds?: boolean;
onlyTempFeeds?: boolean;
};

export type Pagination = {
startIndex: number;
limit: number;
};
export const FeedListRepository = dataSource.getRepository(FeedList).extend({
async getFeedList(
categoryId: number | undefined,
Expand Down Expand Up @@ -131,10 +136,15 @@ export const FeedListRepository = dataSource.getRepository(FeedList).extend({
});
},

async getFeedListByUserId(userId: number, options: FeedListOptions = {}) {
async getFeedListByUserId(
userId: number,
page: Pagination,
options: FeedListOptions = {}
) {
const { includeTempFeeds = false, onlyTempFeeds = false } = options;

let feedListCondition = {};
let orderOption = {};

if (includeTempFeeds && onlyTempFeeds) {
throw {
Expand All @@ -150,14 +160,30 @@ export const FeedListRepository = dataSource.getRepository(FeedList).extend({
} else if (onlyTempFeeds) {
// 사용자의 임시저장 게시글 목록만 반환
feedListCondition = { postedAt: IsNull() };
orderOption = { updatedAt: 'DESC' };
} else {
// 사용자의 정식 게시글 목록만 반환
feedListCondition = { postedAt: Not(IsNull()) };
orderOption = { postedAt: 'DESC' };
}

return await this.find({
let pageCondition = {};
if (page) {
const startIndex: number = (page.startIndex - 1) * page.limit;

pageCondition = {
skip: startIndex,
take: page.limit,
};
}

const findOption = {
where: { userId: userId, deletedAt: IsNull(), ...feedListCondition },
});
order: orderOption,
...pageCondition,
};

return await this.find(findOption);

// --------------------------------------------------------------------------
// 아래의 2 코드를 위 코드로 리팩토링 함 (2023.03.24) ---------------------------------
Expand Down
34 changes: 23 additions & 11 deletions src/routes/users.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,35 +20,47 @@ router.get('/checknickname', asyncWrap(usersController.checkDuplicateNickname));
// 회원가입시 이메일 중복체크하기
router.get('/checkemail', asyncWrap(usersController.checkDuplicateEmail));

// 로그인 유저의 모든 정보 조회하기
// 유저의 모든 정보 조회하기
// 유저의 모든 게시물 가져오기
router.get(
'/userinfo',
asyncWrap(authValidateOrReject),
asyncWrap(usersController.getMe)
'/userinfo/:id?/feeds',
asyncWrap(authValidateOrNext),
asyncWrap(usersController.getUserFeeds)
);

// 타겟 유저의 정보 조회하기
// 유저의 모든 덧글 가져오기
router.get(
'/userinfo/:id?/comments',
asyncWrap(authValidateOrNext),
asyncWrap(usersController.getUserComments)
);
// 유저의 모든 좋아요 가져오기
router.get(
'/userinfo/:id?/symbols',
asyncWrap(authValidateOrNext),
asyncWrap(usersController.getUserFeedSymbols)
);
// 유저 가입정보 확인하기
router.get(
'/userinfo/:id',
'/userinfo/:id?',
asyncWrap(authValidateOrNext),
asyncWrap(usersController.getUserInfo)
asyncWrap(usersController.getUserInfo) // authValidateOrNext
);

// 유저 정보 수정하기
router.patch(
'/userinfo',
'/signup',
asyncWrap(authValidateOrReject),
asyncWrap(usersController.updateUserInfo)
);

// 유저 정보 삭제하기
router.delete(
'/userinfo',
'/signup',
asyncWrap(authValidateOrReject),
asyncWrap(usersController.deleteUser)
);

// 유저 비밀번호 찾기 - 이메일로 비밀번호 재설정 링크 보내기
router.post('/password', asyncWrap(usersController.resetPassword));
router.post('/signup/password', asyncWrap(usersController.resetPassword));

export default router;
2 changes: 1 addition & 1 deletion src/services/comments.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ const deleteComment = async (commentId: number, userId: number) => {
};

const getCommentsById = async (userId: number) => {
return await CommentRepository.getCommentListByUserId(userId);
return await CommentRepository.getCommentListByUserId(userId, undefined);
};
export default {
getCommentList,
Expand Down
10 changes: 7 additions & 3 deletions src/services/feeds.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,13 @@ import { FeedOption } from '../repositories/feed.repository';
// 임시저장 ==================================================================
// 임시저장 게시글 리스트 --------------------------------------------------------
const getTempFeedList = async (userId: number) => {
const results = await FeedListRepository.getFeedListByUserId(userId, {
onlyTempFeeds: true,
});
const results = await FeedListRepository.getFeedListByUserId(
userId,
undefined,
{
onlyTempFeeds: true,
}
);
for (const result of results) {
const updatedAt = result.updatedAt.substring(2);
if (result.title === null) {
Expand Down
Loading

0 comments on commit e2e3633

Please sign in to comment.