250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- django westagram
- crud2
- 자바스크립트
- 실행 컨텍스트
- OSI7계층
- rebase
- async/await
- 노드
- bcrypt
- 프로미스
- on_delete
- JWT
- 장고초기세팅
- westagram
- wecode
- node
- Django
- manytomanyfield
- 호이스팅
- docker
- CORS
- 트랜잭션
- 스코프
- javascript
- Jest
- typescript
- pm2
- nodeJS
- status code
- TypeError: this.boardRepository.createBoard is not a function
Archives
- Today
- Total
될때까지
((TIL)) 프리온보딩 백엔드 사전스터디 : Node.js 3 본문
728x90
배열에 담아 반환되는 쿼리의 실행 결과, 깔끔하게 코드에 적용하기
const user = await myDataSource.query(`
select
id,
email,
nickname,
password
from
users
where
email = ?`, [email])
console.log('user', user)
해당 query의 결과 user를 콘솔에 찍어보면 아래와 같이 배열에 담겨서 반환된다.
user [
{
id: 1,
email: 'codekim@justcode.co.kr',
nickname: 'codeKim',
password: 'c0dek!m'
}
]
배열안에 객체로 담겨서 반환되기 때문에 유저의 유무를 체크할 때도 .length === 0을 사용해서 비교했다.
// 없다 => 없는 유저다
if (user.length === 0) {
console.log('NO_USER')
}
유저가 있다면 bcrypt.compareSync()를 사용해서 비교해야 하는데 이때 첫번째 인자로는 입력한 비밀번호, 두번째 인자는 DB에 저장된 비밀번호가 들어간다. 그러면 true, false로 결과값을 리턴해주는데 user의 쿼리 결과가 배열로 반환되기 때문에 꼭 뒤에 [0]이라는 인덱싱을 사용해서 코드를 적었다.
// 있다 => 유저 데이터 및 유저 비밀번호 디비에서 꺼내오기
bcrypt.compareSync(password, user[0].password)
하지만, 아래처럼 쿼리의 결과 user를 대괄호 [] 안에 담아주면 언패킹이 되서 배열 없이 반환되고 코드가 쪼금 깨끗해졌다 👍
const [user] = await myDataSource.query(`
select
id,
email,
nickname,
password
from
users
where
email = ?`, [email])
...생략...
bcrypt.compareSync(password, user.password)
Object.keys()
객체가 가지고 있는 key값의 이름들을 배열로 반환한다.
const hasKey = { password : false, username : false };
const requireKey = Object.keys(hasKey);
console.log('requireKey', requireKey);
// requireKey [ 'password', 'username' ]
728x90
'프로젝트 > 프리온보딩' 카테고리의 다른 글
((TIL)) 프리온보딩 백엔드 사전스터디 : Node.js 5 (0) | 2022.09.27 |
---|---|
((TIL)) 프리온보딩 백엔드 사전스터디 : Node.js 4 (0) | 2022.09.26 |
((TIL)) 프리온보딩 백엔드 사전스터디 : Node.js 2 (1) | 2022.09.21 |
((TIL)) 프리온보딩 백엔드 사전스터디 : Node.js 1 (1) | 2022.09.20 |
((TIL)) 프리온보딩 백엔드 사전스터디 : Javascript 2 (0) | 2022.09.19 |