Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 23 additions & 9 deletions src/pages/findId/findId.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,24 @@ const emailForm = document.querySelector('form');
const submitButton = document.querySelector('button[type="submit"]');
const emailErrorNotice = document.querySelector('.notice');

inputEmail.addEventListener('input', validationEmail);
inputEmail.addEventListener('input', validateEmail);
emailForm.addEventListener('submit', findId);

/**
* TODO: 거의 다 왔습니다!. 외부에서 input 의 참조를 조달하기 보다는 폼의 이벤트에서 깂을 꺼내면 더 완벽하겠습니다!
* @param e
* @returns {Promise<void>}
*/
async function findId(e) {
e.preventDefault();

const emailValue = inputEmail.value;
const formData = new FormData(e.currentTarget);
const { email } = Object.fromEntries(formData.entries());

try {
const res = await getData('users', {
filter: `email='${emailValue}'`,
filter: `email='${email}'`,
});
Comment on lines 16 to 24
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

거의 다 왔습니다.
form 의 submit 이벤트 사용법을 이해했다면, form 에서 값을 꺼내오는 방법을 배울 차례입니다.


console.log(res);

if (res.length > 0) {
alert(`아이디는 ${res[0].username} 입니다.`);
location.href = '/src/pages/login/';
Expand All @@ -31,11 +34,22 @@ async function findId(e) {
}
}

function validationEmail() {
const isValidEmail = (emailValue) => {
const regexEmail = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const emailValue = inputEmail.value;

if (regexEmail.test(emailValue) || emailValue === '') {
return regexEmail.test(emailValue) || emailValue === '';
};

/**
* TODO: 하나의 함수가 세가지 일을 하고 있군요.
* 1. 이메일 벨리데이션
* 2. 벨리데이션이 실패했을 때의 화면 처리
* 3. 벨리데이션이 성공했을 때의 화면 처리
* 적절하게 추상화해서 함수를 분리하는 것이 좋겠습니다.
* 2와 3항목도 분리해 보시면 어떨까요?
*/
function validateEmail() {
if (isValidEmail(inputEmail.value)) {
emailErrorNotice.classList.remove('block');
emailErrorNotice.classList.add('hidden');
submitButton.classList.remove('bg-button-submit-default');
Comment on lines +37 to 55
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

함수 하나가 세가지 일을 하고 있군요.
함수의 이름을 동사로 바꾸고 벨리데이션 함수만 분리해 보았습니다.
이제 if 블록에 있는 내용물과 else 블록에 있는 내용을 다른 함수로 분리해 보세요.
스스로의 행동을 설명하는 코드가 될 것이라 생각합니다.

Expand Down
11 changes: 8 additions & 3 deletions src/pages/findPassword/findPassword.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,19 @@ inputUserId.addEventListener('input', (e) => {

form.addEventListener('submit', findId);

/**
* TODO: 함수는 입력값에 따라 츨력값이 정해지는 순수함수로 구성하는 것이 가장 좋습니다.
* @param e
* @returns {Promise<void>}
*/
async function findId(e) {
e.preventDefault();

const userIdValue = inputUserId.value;
const formData = new FormData(e.currentTarget);
const { userId } = Object.fromEntries(formData.entries());
Comment on lines 27 to +30
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

폼의 이벤트에서 값을 읽어보면 이벤트 핸들러가 순수함수가 된다는 장점이 있지요.


try {
const res = await getData('users', {
filter: `username='${userIdValue}'`,
filter: `username='${userId}'`,
});

if (res.length > 0) {
Expand Down
4 changes: 2 additions & 2 deletions src/pages/login/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ const loginForm = document.querySelector('#login-form');
loginForm.addEventListener('submit', async (e) => {
try {
e.preventDefault(); // 폼 기본 동작 방지
const formData = new FormData(e.currentTarget);

// 입력값 가져오기
const username = document.querySelector('#username').value;
const password = document.querySelector('#password').value;
const { username, password } = Object.fromEntries(formData.entries());

if (!username || !password) {
alert('아이디 또는 비밀번호를 입력해주세요.');
Expand Down
10 changes: 4 additions & 6 deletions src/util/crud.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { pb } from '/src/api/pocketBase';

// 데이터를 가져오는 함수
async function getData(collectionName, options = {}) {
export async function getData(collectionName, options = {}) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

개인적으로는 눈알이 움직이는 에너지도 아끼기 위해 함수 선언에 export 를 붙입니다.

const response = await pb.collection(collectionName).getFullList({
...options,
});
Expand All @@ -10,18 +10,16 @@ async function getData(collectionName, options = {}) {
}

// 데이터를 생성하는 함수
async function postData(collectionName, data) {
export async function postData(collectionName, data) {
await pb.collection(collectionName).create(data);
}

// 데이터를 수정하는 함수
async function patchData(collectionName, id, data) {
export async function patchData(collectionName, id, data) {
await pb.collection(collectionName).update(id, data);
}

// 데이터를 삭제하는 함수
async function deleteData(collectionName, id) {
export async function deleteData(collectionName, id) {
await pb.collection(collectionName).delete(id);
}

export { getData, postData, patchData, deleteData };
4 changes: 1 addition & 3 deletions src/util/getImageURL.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
function getImageURL(item, fileName = 'image') {
export function getImageURL(item, fileName = 'image') {
return `${import.meta.env.VITE_PB_URL}/api/files/${item.collectionId}/${
item.id
}/${item[fileName]}`;
}

export { getImageURL };
4 changes: 1 addition & 3 deletions src/util/insertTemplate.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function insertTemplate(target, template) {
export function insertTemplate(target, template) {
if (typeof target !== 'string')
throw new Error('target은 문자열이어야 합니다.');

Expand All @@ -8,5 +8,3 @@ function insertTemplate(target, template) {

targetElement.insertAdjacentHTML('beforeend', template);
}

export { insertTemplate };