Skip to content

Commit

Permalink
Merge pull request #151 from prgrms-fe-devcourse/150-feature/localsto…
Browse files Browse the repository at this point in the history
…rage

Feat: HeartStorage, ReviewStorage
  • Loading branch information
shlee9999 authored Oct 4, 2024
2 parents a563afb + 3cebf06 commit c056489
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/utils/HeartStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
type HeartItemType = {
id: string;
};
export default class HeartStorage {
private static readonly KEY = 'heartList';

static getHeartList(): HeartItemType[] {
const heartList = localStorage.getItem(this.KEY);
return heartList ? JSON.parse(heartList) : [];
}

private static setHeartList(newHeartList: HeartItemType[]): void {
localStorage.setItem(this.KEY, JSON.stringify(newHeartList));
}

static addHeart(heart: HeartItemType): void {
const heartList = this.getHeartList();
heartList.push(heart);
this.setHeartList(heartList);
}

static removeHeart(id: string): void {
const heartList = this.getHeartList();
const updatedHeartList = heartList.filter(heart => heart.id !== id);
this.setHeartList(updatedHeartList);
}
}
49 changes: 49 additions & 0 deletions src/utils/ReviewStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
type ReviewItemType = {
review: string;
id: string;
};

export default class ReviewStorage {
private static readonly KEY = 'reviewList';

static getReviewList(): ReviewItemType[] {
const reviewList = localStorage.getItem(this.KEY);
return reviewList ? JSON.parse(reviewList) : [];
}

private static setReviewList(newReviewList: ReviewItemType[]): void {
localStorage.setItem(this.KEY, JSON.stringify(newReviewList));
}

static addReview(review: ReviewItemType): void {
const reviewList = this.getReviewList();
reviewList.push(review);
this.setReviewList(reviewList);
}

static removeReview(id: string): void {
const reviewList = this.getReviewList();
const updatedReviewList = reviewList.filter(review => review.id !== id);
this.setReviewList(updatedReviewList);
}

static editReview(newReview: ReviewItemType): void {
const reviewList = this.getReviewList();
const updatedReviewList = reviewList.map(review => (review.id === newReview.id ? newReview : review));
this.setReviewList(updatedReviewList);
}

static saveReview(review: ReviewItemType): void {
const reviewList = this.getReviewList();
const existingReview = reviewList.find(item => item.id === review.id);

if (existingReview) {
if (review.review === '')
this.removeReview(review.id); // review 파트가 비어있다면 삭제
else this.editReview(review); // 이미 존재하는 리뷰인 경우 editReview 실행
} else {
// 새로운 리뷰인 경우 addReview 실행
this.addReview(review);
}
}
}

0 comments on commit c056489

Please sign in to comment.