ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [데브코스] 27일차 TIL
    TIL/교육 내용 정리 2024. 5. 4. 22:34

    로그인 기본 로직

    // user-demo.js
    app.post('/login', (req, res)=>{
        // body로 userId (인덱스 용도의 id가 아닌.) , pwd 받아야지
        // userUd 가 db에 저장된 회원인지 확인을 해야지
        const {userId, password} = req.body
        db.forEach(function(user, id){
            if(user.userId === userId){
                console.log("같은 거 찾았다.")
                // pwd도 맞는 지 비교
                if(user.password === password){
                    console.log("패스워드도 같다.")
                }else{
                    console.log("패스워드는 틀렸다.")
                }
            }
        })
    })
    

    로그인 예외 처리

    // user-demo.js
    app.post('/login', (req, res)=>{
        console.log(req.body)
        // body로 userId (인덱스 용도의 id가 아닌.) , pwd 받아야지
        // userUd 가 db에 저장된 회원인지 확인을 해야지
        const {userId, password} = req.body
    
        var loginUser = {} // 아무리 값이 비어도 값이 있는 거로
    
        db.forEach(function(user, id){
            if(user.userId === userId){
                loginUser = user
            }
        })
        // userId 값을 못 찾았으면..
        if(loginUser){
            console.log("같은 거 찾았다.")
            // pwd도 맞는 지 비교
            if(loginUser.password === password){
                console.log("패스워드도 같다.")
            }else{
                console.log("패스워드는 틀렸다.")
            }
        }else{
            console.log("입력하신 아이디는 없는 아이디 입니다.")
        }
    })
    

    JS Object.keys()

    <aside> 💡 빈 객체 확인하는 방법 3가지

    </aside>

    {}

    1. 객체.keys()
    2. for in
    3. lodash : isEmpty
    //empty-demo.js
    const obj1 = {}
    const obj2 = {message : "안 빔"}
    
    console.log(Object.keys(obj1))   // length === 0
    console.log(Object.keys(obj2))   // length === 1
    
    // 결과
    []
    [ 'message' ]
    
    const obj1 = {}
    const obj2 = {message : "안 빔"}
    const num = 1
    const str1 = "one"
    const str2 = ""
    
    console.log(Object.keys(obj1).length ===0)
    console.log(Object.keys(obj2).length ===0)
    console.log(Object.keys(num).length ===0)
    console.log(Object.keys(str1).length ===0)
    console.log(Object.keys(str2).length ===0)
    
    // 결과
    true
    false
    true
    false
    true
    
    // 함수를(모듈) 만들어서 사용
    const obj1 = {}
    console.log(isEmpty(obj1))
    
    function isEmpty(obj){
        //if(obj.constructor === Object)
        if(Object.keys(obj).length === 0 ){
            return true;
        }else{
            return false;
        }
    }
    

    로그인 고도화

    //user-demo.js
    // 로그인
    app.post('/login', (req, res)=>{
        console.log(req.body)
        // body로 userId (인덱스 용도의 id가 아닌.) , pwd 받아야지
        // userUd 가 db에 저장된 회원인지 확인을 해야지
        const {userId, password} = req.body
    
        var loginUser = {} // 아무리 값이 비어도 값이 있는 거로
    
        db.forEach(function(user, id){
            if(user.userId === userId){
                loginUser = user
            }
        })
        // userId 값을 못 찾았으면..
        if(isExisted(loginUser)){
            console.log("같은 거 찾았다.")
            // pwd도 맞는 지 비교
            if(loginUser.password === password){
                console.log("패스워드도 같다.")
            }else{
                console.log("패스워드는 틀렸다.")
            }
        }else{ // length === 0 일 때
            console.log("입력하신 아이디는 없는 아이디 입니다.")
        }
    })
    
    function isExisted(){
        if(Object.keys(obj).length){
            return true
        }else{
            return false
        }
    }
    

    채널 API 설계 1탄(URL, http method/status, res/req)

    채널

    • 채널 생성
      • POST /channels
        • req : body channelTitle
        • res 201 : ${channelTitle}님 채널을 응원합니다.] 👉다른 페이지..ex)채널관리페이지
    • 채널 개별 수정
      • PUT /channel/:id
        • req : URL (id), body channelTitle
        • res 200 : 채널명이 성공적으로 수정되었습니다. 기존 : ${} ->수정 ${} 👉화면도 나중.....
    • 채널 개별 삭제
      • DELETE /channels/:id
        • req : URL(id)
        • res 200 : 삭제 되었습니다. 👉 메인페이지
    • 채널 전체 조회
      • GET /channels
        • req : x
        • res 200 : 채널 전체 데이터 list, json array
    • 채널 개별 조회
      • GET /channels/:id
        • req : URL (id)
        • res 200 : 채널 개별 데이

    채널 API 설계 2탄

    • 삭제는 채널관리 수정버튼 옆에 개별 삭제 버튼 놓자
    • 채널관리 페이지에도 생성 버튼도 놓자

    채널 생성, 채널 개별 조회

    // channel-demo.js
    app
        .route('/channels')
        .get((req, res) =>{
            res.send("전체조회")
        })// 채널 전체 조회
        .post((req, res)=>{
            if(req.body.channelTitle){
                db.set(id++, req.body)
                res.status(201).json({
                    message : `${db.get(id-1).channelTitle} 채널을 응원합니다!`
                })
            }else{
                res.status(400).json({
                    message : `요청 값을 제대로 보내주세요.`
                })
            }
        })// 채널 개별 생성 = db에 저장
    
    app
        .route('/channels/:id')
        .get((req, res)=>{
            let {id} = req.params
            id = parseInt(id)
            
            var channel = db.get(id)
    
            if(channel){
                res.status(200).json(channel)
            }else{
                res.status(404).json({
                    message :`채널 정보를 찾을 수 없습니다.`
                })
            }
    
        })  // 채널 개별 조회
    

    채널 개별 삭제, 개별 수정

    // channel-demo.js
    .put((req, res)=>{
            let {id} = req.params
            id = parseInt(id)
    
            var channel = db.get(id)
            var oldTilte = channel.channelTitle
    
            if(channel){
                var newTitle = req.body.channelTitle
    
                channel.channelTitle = newTitle
                db.set(id, channel)
    
                res.json({
                    message : `채널명이 정상적으로 수정되었습니다. 기존 : ${oldTilte}에서 수정 : ${newTitle}`
                })
            }else{
                res.status(404).json({
                    message :`채널 정보를 찾을 수 없습니다.`
                })
            }
    
        }) // 채널 개별 수정
        .delete((req, res)=>{
            let {id} = req.params
            id = parseInt(id)
            
            var channel = db.get(id)
    
            if(channel){
                db.delete(id)
                res.status(200).json({
                    message : `${channel.channelTitle}이 정상적으로 삭제되었습니다.`
                })
            }else{
                res.status(404).json({
                    message :`채널 정보를 찾을 수 없습니다.`
                })
            }
        })// 채널 개별 삭제
    

    채널 전체 조회

    // channel-demo.js
    app
        .route('/channels')
        .get((req, res) =>{
            var channels = {} // json 형태 소괄호 리스트(배열)
            // 하나씩 맵에서 꺼내서 channels에 넣어줄거
            db.forEach(function(value, key){
                channels[key] = value
            })
    
            console.log(channels)
        })
    
    • json array 보단 json형태로 1 이라는 key 값에 value를 추가…
    • 그러면 json array 어떻게 나타내지 ❓
      // channel-demo.js
      app
          .route('/channels')
          .get((req, res) =>{
              var channels = [] // json 형태 리스트 대괄호
              // 하나씩 맵에서 꺼내서 channels에 넣어줄거
              db.forEach(function(value, key){
                  channels.push(value)
              })
      
              console.log(channels)
          })
      
      // 출력 결과
      [
        { channelTitle: '날아라송아' },
        { channelTitle: '걸어라송아' },
        { channelTitle: '날아라송아' }
      ]
      
      • 그러면 이렇게 value만 push하면 프론트엔드에서 어떻게 꺼내니 ❓
        • 그러면 어떻게 json형태로 쓸 수 있을 까 ❓
        • res.json(channels)
      • 배열이기 때문에 인덱스 활용하면 된다. ex) console.log(channel[0]) → 날아라송아
    • [ ]:리스트,(배열)

    전체 조회 고도화 (데이터가 없을 때)

    //channel-demo.js
    app
        .route('/channels')
        .get((req, res) =>{
            if(db.size){
                var channels = [] // json 형태
            // 하나씩 맵에서 꺼내서 channels에 넣어줄거
            db.forEach(function(value, key){
                channels.push(value)
            })
    
            res.json(channels)
            }else{
                res.status(404).json({
                    message : `조회할 채널이 없습니다.`
                })
            }
        })// 채널 전체 조회
    

    'TIL > 교육 내용 정리' 카테고리의 다른 글

    [데브코스] 30일차 TIL  (0) 2024.05.07
    [데브코스] 28일차 TIL  (0) 2024.05.05
    [데브코스] 26일차 TIL  (0) 2024.05.04
    [데브코스] 25일차 TIL  (0) 2024.05.04
    [데브코스] 24일차 TIL  (0) 2024.05.04
Designed by Tistory.