-
항해 99 5기 TIL_38항해 99 2022. 2. 17. 04:05
▶ Today I Learned
<CS>
[캐시]
캐시(cache, 문화어: 캐쉬, 고속완충기, 고속완충기억기)는 컴퓨터 과학에서 데이터나 값을 미리 복사해 놓는 임시 장소를 가리킨다. 캐시는 캐시의 접근 시간에 비해 원래 데이터를 접근하는 시간이 오래 걸리는 경우나 값을 다시 계산하는 시간을 절약하고 싶은 경우에 사용한다. 캐시에 데이터를 미리 복사해 놓으면 계산이나 접근 시간 없이 더 빠른 속도로 데이터에 접근할 수 있다.
캐시 히트: RAM에서 찾는 데이터가 CPU내 캐시 내 있을 경우
캐시 미스: RAM에서 찾는 데이터가 CPU내 캐시 내 없을 경우
<홈페이지 구현>
[dotenv]
로그인과 게시글, 댓글 기능이 있는 새로운 페이지를 만드는 중에 있다.
require('dotenv').config();
dotenv는 무엇인가?
공식문서에 따르면 다음과 같다.
"Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env."
즉, 환경 변수를 .env(ironment) 파일에서 process.env파일로 옮겨주는 의존성 제로 모듈이다.
사용 시에는 아래와 같은 코드들이 필요하다.
# install locally (recommended) npm install dotenv --save
require('dotenv').config() console.log(process.env)
S3_BUCKET="YOURS3BUCKET" SECRET_KEY="YOURSECRETKEYGOESHERE"
또한 .env 내에서 #는 주석처리에 쓰이므로 만약 어떤 요소 중 #가 포함되어 있다면 주석이 아님을 밝히기위해 해당 코드를
따옴표로 감싸야 한다.
그 외 자세한 설명은 하단 공식문서 링크를 참조해보자.
https://www.npmjs.com/package/dotenv
그렇다면 환경변수는 왜 사용하는가?
아래의 링크에 따르면 다음과 같다.
"dotenv allows you to separate secrets from your source code. This is useful in a collaborative environment (e.g., work, or open source) where you may not want to share your database login credentials with other people. Instead, you can share the source code while allowing other people to create their own .env file."
즉, 소스코드로 부터 보안사항(비밀사항)들을 분리시킬 수 있기 때문이다. 이런 환경 변수를 사용해 다른 사람들과 데이터베이스 로그인 자격증명을 공유하지 않을 수 있다. 사람들에게는 소스코드만 공유해주므로 그 사람들도 자기만의 .env 파일을 만들 수 있다.
[bcrypt]
패스워드를 해쉬화 하는데 쓰이는 npm 내 라이브러리,
node-gyp이라는 것을 기반으로 하며 이 node-gyp은 안정적인 버전의 node에서만 동작하므로
bcrypt 를 사용할 때 역시 안정적인 버전의 node를 사용하여야 한다.
사용법은 다음과 같다.
모듈 설치
npm install bcrypt
비밀 번호에 쓸 해쉬 직접 생성하여 해쉬화 (비밀번호를 해쉬로 교체하는 것)
bcrypt.genSalt(saltRounds, function(err, salt) { bcrypt.hash(myPlaintextPassword, salt, function(err, hash) { // Store hash in your password DB. }); });
해쉬 자동 생성하고 비밀번호를 해쉬화
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) { // Store hash in your password DB. });
현재 프로젝트에서는 이렇게 사용되었다.
bcrypt.genSalt(8, (err, salt) => { if (err) return next(err); bcrypt.hash(user.password, salt, (err, hash) => { if (err) return next(err); user.password = hash; next(); }) }) // 기존 비밀번호와 비교 실시 UserSchema.methods.compare = function (password) { let user = this; return bcrypt.compareSync(password, user.password); };
여기서 saltRounds 부분이 8이라는 말은 아래를 가리킨다.
rounds=8 : ~40 hashes/sec
우와 같이 비밀번호 해쉬가 가능하다.
좀 더 상세한 내용은 하단의 공식 문서 참조
https://www.npmjs.com/package/bcrypt
[virtual]
a virtual is a property that is not stored in MongoDB
Mongo DB에는 저장되지 않는 가상의 프로퍼티이다.
어떤 특정한 모델을 만들고는 싶으나 DB에 따로 저장을 하지 않는 경우 사용하는 듯 하다.
현재는 팀원 분이 이런 식으로 사용하셨다.
UserSchema.virtual("userId").get(function () { return this._id.toHexString(); }); UserSchema.set("toJSON", { virtuals: true, });
저기서 userId라는 가상의 값을 만드는데 해당 스키마에 있는 DB 상의 id 값을 가져온 다음 24비트의 hex문자열로 바꿔주고 있다.
그리고 아래에서 그것을 JSON형태로 바꾸어 주고 있다.
상세한 설명은 하단의 링크를 참조하면 좋다.
https://mongoosejs.com/docs/tutorials/virtuals.html
▶ 느낀 점
프로젝트 코드를 뜯어보면서 이런 지식도 있구나하며 감탄했다.
새로운 지식을 배우고 나니 코드의 구조나 기능이 보이는 것도 정말 신기했다.
비록 공부할 것은 많지만 이렇게 또 하나를 알아가고 성장해가는 내 모습에 기분이 뿌듯했다.
물론 공부해야할 것은 여전히 많고 알고리즘 풀이도 밀려있긴 하지만..
계속해나갈 것이니 큰 문제는 없을 듯 하다..!
화이팅..!
▶ 공부 시 참고 링크들
https://www.zerocho.com/category/NodeJS/post/5950a6c4f7934c001894ea83
https://mobicon.tistory.com/302
https://taesung1993.tistory.com/46
'항해 99' 카테고리의 다른 글
항해 99 5기 TIL_40 (0) 2022.02.19 항해 99 5기 TIL_39 (0) 2022.02.18 항해 99 5기 TIL_37 (0) 2022.02.16 항해 99 5기 TIL_36 (0) 2022.02.15 항해 99 5기 WIL_5 (0) 2022.02.13