Mi Lugarcito

Node.js - Twitter Clone Coding // Search page 본문

Express.js

Node.js - Twitter Clone Coding // Search page

selene park 2021. 4. 3. 14:55

 

 

1. routes/searchRoutes.js 새로 만들기(page 먼저 연동하기 및 각 상세 경로 세팅)

const express = require('express');
const app = express();
const router = express.Router();
const bodyParser = require("body-parser");
const User = require('../schemas/UserSchema');
//password hash작업하기
const bcrypt = require("bcrypt");


router.get("/", (req, res, next)=>{
    var payload=createPayload();
    res.status(200).render("searchPage", payload); 
})

router.get("/:selectedTab", (req, res, next)=>{
    var payload=createPayload();
    payload.selectedTab = req.params.selectedTab;
    res.status(200).render("searchPage", payload); 
})

function createPayload(){
    return {
        pageTitle: "Search",
        userLoggedIn: req.session.user,
        userLoggedInJs: JSON.stringify(req.session.user)
    }
}

module.exports = router;

 

2. pug

3. app.js

 

 

 

 

 

 

4. css

 

 

5. public/js/search.js -->event handler 담당

 

 

 

 

public/js/search.js (request 요청, database,  event handler 담당)

//event handler

var timer;



$("#searchBox").keydown(()=>{
    //console.log("he");
    clearTimeout(timer);
    var textbox =$(event.target);
    var value = textbox.val();//value (js)와 val(jquery) 차이
    var searchType = textbox.data().search;

    timer = setTimeout(()=>{
        value = textbox.val().trim();

        if(value === ""){
            $(".resultContainer").html("");//clear this container
        }else{
            //console.log(value);
            search(value, searchType);
        }

    }, 1000)//1초 이후에 화살표 함수 실행한다




    // console.log(value);
    // console.log(searchType);
})



function search(searchTerm, searchType){
    var url = searchType ==="users" ? "/api/users" : "/api/posts"

    $.get(url, { search : searchType }, (results)=>{//callback
        console.log(results);
    })

}

 

 

routes/api/post.js (request handling 해서 response 경로 조건 반환)

 

router.get("/", async (req, res, next)=>{//<pending> 된 상태 해결


    //profile
    var searchObj = req.query; // searchObj 는 posts.js의 { postedBy: profileUserId, isReply : false }, 를 의미 

    //Posts 와 Replies를 구분하기 위해서
    if(searchObj.isReply !==undefined){
        var isReply = searchObj.isReply=="true"
        searchObj.replyTo = { $exists: isReply};//mongoDB에서 isReply가 true면 replyTo 가 존재하는것 & false면 replyTo가 존재하지 않는것$
        delete searchObj.isReply;

        //console.log(this.searchObj);
    }

    //search
    if(searchObj.search !==undefined){
        //regex => like 와 같은것 
        //$options : "i" 뭐임?
        searchObj.content = { $regex : searchObj.search, $options : "i"}
        delete searchObj.search;

    }










    if(searchObj.followingOnly !==undefined){
        var followingOnly = searchObj.followingOnly=="true";

        if(followingOnly){
            var objectIds =[];

            if(!req.session.user.following){//!req.session.user.following -> if doesn't exist
                req.session.user.following=[];
            }

            //User 테이블에서 배열로 선언됨
            req.session.user.following.forEach(user=>{
                objectIds.push(user);
            });

            objectIds.push(req.session.user._id);
            searchObj.postedBy = { $in: objectIds};
        }
        delete searchObj.followingOnly;

    }



    //message으로 사용했다가 profile 용 filter로 변환 (둘다 목적에 맞게 작동함 -> 근거 : 아래 getPosts 함수를 filter 라고 정의해서)
    var results = await getPosts(searchObj);//<pending> 된 상태 해결
    //console.log(results);//<pending> 된 상태였음
    res.status(200).send(results);

})

 

 

routes/searchRoutes.js 

 

 

routes/api/users.js

//search
router.get("/", async (req, res, next)=>{
    var searchObj = req.query;
    if(req.query.search !== undefined){
        searchObj ={
            $or :[
                {firstName : { $regex : req.query.search, $options : "i"}},
                {lastName : { $regex : req.query.search, $options : "i"}},
                {userName : { $regex : req.query.search, $options : "i"}}
            ]
        }
    }

    //find
    User.find(searchObj)
        .then(results => res.status(200).send(results))
        .catch(error=>{
            console.log(error);
            res.sendStatus(400);
        })

});

 

public/js/search.js

 

 

 

 

public/js/common.js (ajax, 버튼이벤트연결)