금일 달성 항목
1) front 지원하기 기능 및 페이지 제작
: user, company로 분기하여 제작
문제 해결 과정 1 - 지원하기 페이지 제작
[문제]
보통 아래와 같은 코드로 id 값을 불러오는데 apply는 구직자 or 회사에 따라 화면에 변경되므로 아래와 같은 코드를 작성하게되면
'user','password' 가 나온다 이 값을 활용하여 같은 화면에서의 분기가 가능했지만.
const type = window.location.pathname.split('/')[2];
지원취소와 같은 DELETE를 하기 위해서는 jobpostingId를 가져와야하는 상황이었지만 위와 같이 split을 사용할 수도 없고, 백단에서 @Query를 통해 가져오는 것도 되지 않아 어떻게 하면 id값을 가져올지 고민하는 상황이었습니다.
const response = await fetch(`/api/applications/${jobpostingId}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
});
실패
// 채용공고 아이디 가져오기
@Get('getId')
getJobpostingId(@Query('id') id: string) {
return this.jobpostingService.getJobpostingId({ id: Number(id) });
}
실패
// 채용공고 아이디 가져오기
async getJobpostingId({ id }: { id: number }) {
const jobposting = await this.jobpostingRepository.findOne({
where: { id },
}); // 쿼리 조건을 추가하여 원하는 jobposting 가져옴
console.log(jobposting);
if (!jobposting) {
throw new Error('채용공고를 찾을 수 없습니다.');
}
return jobposting.id; // jobposting의 id 속성 반환
}
[시도 및 해결]
생각보다 방법은 간단했습니다.
apply 가져올때 relations로 jobposting을 가져오기 때문에 이 값을 활용하여
applicant.service.ts
// 내가 지원한 공고 가져오기
async getJobpostingById(id: number) {
const applications = await this.applicantRepository.find({
where: { userId: id },
relations: ['jobposting'], // 채용공고 정보를 함께 가져오기 위해 관계 설정
});
const jobpostings = applications.map(
(application) => application.jobposting,
);
return jobpostings;
}
apply 값을 뿌려줄때 data-id영역의 applyUser.id 즉 jobpostingId를 가져와 사용하면 되는 것 이었습니다.
async function getAppliesUser() {
try {
if (type === 'user') {
const response = await fetch('/api/applications/user');
const applyUserData = await response.json();
const temp = applyUserData
.map((applyUser) => {
return `
<div class="apply-card">
<h4>${applyUser.title}</h4>
<h6>근무지 : ${applyUser.workArea}</h6>
<h6>마감일 : ${applyUser.dueDate}</h6>
</div>
<button
type="button"
class="btn btn-outline-primary apply-btn"
data-id=${applyUser.id}
>
지원 취소
</button>
<hr>
`;
})
.join('');
applyBox.innerHTML = temp;
최종적으로 아래와 같은 코드로 불러올 수 있었습니다.
async function getAppliesUser() {
try {
if (type === 'user') {
const response = await fetch('/api/applications/user');
const applyUserData = await response.json();
const temp = applyUserData
.map((applyUser) => {
return `
<div class="apply-card">
<h4>${applyUser.title}</h4>
<h6>근무지 : ${applyUser.workArea}</h6>
<h6>마감일 : ${applyUser.dueDate}</h6>
</div>
<button
type="button"
class="btn btn-outline-primary apply-btn"
data-id=${applyUser.id}
>
지원 취소
</button>
<hr>
`;
})
.join('');
applyBox.innerHTML = temp;
const applyBtns = document.querySelectorAll('.apply-btn');
applyBtns.forEach((applyBtn) => {
applyBtn.addEventListener('click', async (event) => {
const jobpostingId = event.target.getAttribute('data-id');
console.log(jobpostingId);
const result = confirm('확인 버튼을 누르면 지원이 취소됩니다.');
if (result === true) {
const response = await fetch(`/api/applications/${jobpostingId}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
});
if (response.ok) window.location.reload();
alert('지원이 취소되었습니다.');
} else if (result === false) {
alert('취소 되었습니다.');
}
});
});
[알게된 점]
생각보다 개발은 요소를 잡아내는 낚시꾼 같은 기질이 필요하다 생각했습니다.
'혼자 고민해보기_ 개발 > TIL (Today I Learned)' 카테고리의 다른 글
20230907(목)_ 최종프로젝트 진행 (1) | 2023.09.08 |
---|---|
20230906(수)_ 최종프로젝트 진행 (0) | 2023.09.06 |
20230904(월)_ 최종프로젝트 진행 (0) | 2023.09.04 |
20230901(금)_ 최종프로젝트 진행 (0) | 2023.09.02 |
20230831(목)_ 최종프로젝트 진행 (0) | 2023.09.02 |