Skip to content

Commit

Permalink
feat: 차단리스트 엔티티 생성, makeBlockUser 라우터 추가, 차단 사용자 이벤트 필터링 실패에~
Browse files Browse the repository at this point in the history
  • Loading branch information
seohyun-kim committed Mar 7, 2022
1 parent 0bedd82 commit cd01fd0
Show file tree
Hide file tree
Showing 9 changed files with 152 additions and 4 deletions.
35 changes: 35 additions & 0 deletions src/entity/BlockedList.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, OneToMany, PrimaryGeneratedColumn} from 'typeorm'
import User from './User'
import {Infer} from '../common/utils/zod';
import {BlockUserResponseScheme} from './schemes';
import BaseBetterEntity from '../common/base/BaseBetterEntity';

@Entity()
export default class BlockedList extends BaseBetterEntity {
static relations = ['user'];

@PrimaryGeneratedColumn({comment: '식별자.'})
id: number

@ManyToOne(() => User, (u) => u.events)
@JoinColumn()
blockingUser: User;

@ManyToOne(() => User, (u) => u.events)
@JoinColumn()
blockedUser: User;

@CreateDateColumn({comment: '차단 일시.'})
createdAt: Date;


async toResponse(userId?: number): Promise<Infer<typeof BlockUserResponseScheme>> {
return {
id: this.id,
blockingUserId: this.blockingUser.id,
blockedUserId: this.blockedUser.id,
createdAt: this.createdAt

}
}
}
3 changes: 2 additions & 1 deletion src/entity/Event.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, OneToMany, PrimaryGeneratedColumn} from 'typeorm'
import User from './User'
import Comment from './Comment'
import BlockedList from './BlockedList'
import {Infer} from '../common/utils/zod';
import LikeService from '../service/LikeService';
import EventLike from './EventLike';
Expand All @@ -12,7 +13,7 @@ import BaseBetterEntity from '../common/base/BaseBetterEntity';

@Entity()
export default class Event extends BaseBetterEntity {
static relations = ['user', 'comments', 'likes', 'notifications'];
static relations = ['user', 'comments', 'likes', 'notifications', 'user.BlockedList'];

@PrimaryGeneratedColumn({comment: '식별자.'})
id: number
Expand Down
7 changes: 7 additions & 0 deletions src/entity/User.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {Column, CreateDateColumn, Entity, OneToMany, PrimaryGeneratedColumn} from 'typeorm';
import Event from './Event';
import Comment from './Comment';
import BlockedList from './BlockedList';
import {Infer} from '../common/utils/zod';
import EventNotification from './EventNotification';
import EventLike from './EventLike';
Expand Down Expand Up @@ -74,6 +75,12 @@ export default class User extends BaseBetterEntity {
@OneToMany(() => EventNotification, (n) => n.event)
notifications: EventNotification[];

/**
* 사용자가 차단한 사용자들.
*/
@OneToMany(() => BlockedList, (b) => b.blockingUser)
BlockedList: BlockedList[];

getSubscription() {
return this.subscribing;
}
Expand Down
12 changes: 12 additions & 0 deletions src/entity/schemes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,15 @@ export const UpdateMeRequestScheme = {
nickname: z.string(),
imageUuid: z.string().optional().nullable()
};

export const BlockUserRequestScheme = {
blockedUserId: z.number()
};

export const BlockUserResponseScheme = {
id: z.number(),
blockingUserId: z.number(),
blockedUserId: z.number(),
createdAt: z.date()
}

2 changes: 1 addition & 1 deletion src/server/middleware/authorizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ export function authorizer<TParams = any, TQuery = any, TBody = any>(): RequestH
};
}

function extractJwt(req: express.Request<any, any, any, any>): string | undefined {
export function extractJwt(req: express.Request<any, any, any, any>): string | undefined {
return req.header('token') ?? req.cookies[config.server.jwt.cookieName];
}
20 changes: 20 additions & 0 deletions src/server/routes/block/makeBlockUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {defineSchema} from '../../libs/schema';
import {defineRoute} from '../../libs/route';
import {authorizer} from '../../middleware/authorizer';
import {BlockUserRequestScheme} from "../../../entity/schemes";
import BlockingService from "../../../service/BlockingService";


const schema = defineSchema({
summary: '차단할 사용자를 지정합니다.',
description: '네.',

body: BlockUserRequestScheme
});

export default defineRoute('post', '/blockuser', schema, authorizer(), async (req, res) => {
const userId = req.requireUserId();
await BlockingService.makeBlock(userId, req.body);

res.send();
});
15 changes: 13 additions & 2 deletions src/server/routes/events/getEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import {defineSchema} from '../../libs/schema';
import {defineRoute} from '../../libs/route';
import EventService from '../../../service/EventService';
import {EventResponseScheme} from '../../../entity/schemes';
import {extractJwt} from "../../middleware/authorizer";
import Event from "../../../entity/Event";


const schema = defineSchema({
summary: '행사를 다 가져옵니다.',
Expand All @@ -13,7 +16,15 @@ const schema = defineSchema({
export default defineRoute('get', '/events', schema, async (req, res) => {
const {userId} = req;

const eventInformation = await EventService.getEvents();

// 잘 안됨 ㅠ
let eventInformation;
if(extractJwt(req)) { //로그인 정보가 있는 경우
console.log("로그인 정보 있음!");
eventInformation = await EventService.getEventsWithoutBlockedUser(req.requireUserId());
}else{
// 로그인 정보가 없는 경우 모든 이벤트 다 가져옴!
console.log("로그인 정보 없어요");
eventInformation = await EventService.getEvents();
}
return res.json(await Promise.all(eventInformation.map(e => e.toResponse(userId))))
});
32 changes: 32 additions & 0 deletions src/service/BlockingService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import Event from '../entity/Event';
import {log} from '../common/utils/log';
import {preview} from '../server/libs/json';
import User from '../entity/User';
import Comment from '../entity/Comment';
import EventLike from '../entity/EventLike';
import EventNotification from '../entity/EventNotification';
import UserService from './UserService';
import SubscriptionService from './SubscriptionService';
import {Infer} from '../common/utils/zod';
import {BlockUserRequestScheme, EventRequestScheme} from '../entity/schemes';
import BlockedList from "../entity/BlockedList";

class BlockingService {

async makeBlock(userId: number, body: Infer<typeof BlockUserRequestScheme>): Promise<BlockedList> {
const blockingUser = await UserService.getUser(userId);

const blockList = await BlockedList.create({
blockingUser: blockingUser,
blockedUser: body.blockedUserId,
}).save();

log(`[사용자${blockingUser.id}]가 [사용자${preview(body.blockedUserId)}] 를 차단합니다.`);
return blockList;
}



}

export default new BlockingService();
30 changes: 30 additions & 0 deletions src/service/EventService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import {preview} from '../server/libs/json';
import User from '../entity/User';
import Comment from '../entity/Comment';
import EventLike from '../entity/EventLike';
import BlockedList from "../entity/BlockedList";
import EventNotification from '../entity/EventNotification';
import UserService from './UserService';
import SubscriptionService from './SubscriptionService';
import {Infer} from '../common/utils/zod';
import {EventRequestScheme} from '../entity/schemes';
import {authorizer} from "../server/middleware/authorizer";

class EventService {
async makeEvent(userId: number, body: Infer<typeof EventRequestScheme>): Promise<Event> {
Expand Down Expand Up @@ -42,6 +44,34 @@ class EventService {
return await Event.find({order: {id: 'DESC'}});
}

// 안됨 ㅠㅠ
async getEventsWithoutBlockedUser(userId: number): Promise<Event[]> {

return await Event.createQueryBuilder('event')
/** relations 필드 가져오는 부분 */
.leftJoinAndSelect('event.user', 'user')
.leftJoinAndSelect('event.comments', 'comments')
.leftJoinAndSelect('event.likes', 'likes')
.leftJoinAndSelect('event.notifications', 'notifications')
// .leftJoinAndSelect('user.blockingUser', 'blockingUser')
// .leftJoinAndSelect('user.blockedUser', 'blockedUser')

/** where 절을 위한 join(select는 안 함) */
.leftJoin('event.user', 'user')
.leftJoin('user.BlockedList', 'blocked_list')
.leftJoin('blocked_list.blockingUser', 'blocking_user')
.leftJoin('blocked_list.blockedUser', 'blocked_user')
.where(':userId NOT IN blocked_user.id', {userId: userId})

.getMany(); // group by 안해도 얘가 잘 처리해줌 ^~^

// ㅠㅠ
// return await Event.query(`SELECT * FROM Event
// WHERE user_id NOT IN (SELECT blocked_user_id FROM Blocked_list WHERE blocking_user_id=${userId})`);
// }
}


/**
* 내가 댓글을 단 Event를 모두 가져오기.
* @param userId 내 사용자 id.
Expand Down

0 comments on commit cd01fd0

Please sign in to comment.