lky473736 / forum-express

(project) Community and Forum Service with express.js and node.js
Apache License 2.0
0 stars 0 forks source link

forum-express : log 3 #4

Open lky473736 opened 6 months ago

lky473736 commented 6 months ago

forum-express - log 3

글 보기, 글 상세 페이지, 글 작성 기능을 구현하자.

항상 어떤 기능 (feature)을 만들거나 무언가를 debugging해야할 때 무작정 그 기능에 대해 검색하는 것보다는 먼저 한글로 시나리오를 작성하는 연습이 매우 중요한 것 같다.


글 보기 기능

시나리오

app.get('/list', async (요청, 응답) => {
    // 글 보여줄 글목록을 db로부터 가지고 오기
    let postlist = await db.collection('post').find().toArray();
    console.log(postlist);

    // ejs 띄우기
    응답.render('list.ejs', {글목록 : postlist});
});

글 상세 페이지

시나리오

app.get('/detail/:id', async(요청, 응답) => {
  try {
    let posting = await db.collection('post').findOne({_id : new ObjectId(요청.params.id)});
    console.log(요청.params.id); 

    if (posting != null) { // 만약 posting이 null이 아니면
      응답.render('detail.ejs', {글 : posting});
    }

    else { // posting이 null이면
      응답.send("<script>alert('존재하지 않는 게시물입니다.'); window.location.replace('/list');</script>");
    }
  } catch (err) {
    console.log('error occurred');
    return 응답.status(404).send('user error occurred');
    // 404는 유저잘못이라는 뜻임
  }
});

글 작성 기능

시나리오

app.get('/write', async(요청, 응답) => {
    응답.render('write.ejs');
});

app.post('/add', async(요청, 응답) => {
    // 요청.body : 유저가 보낸 데이터를 출력 가능 
    // -> body 사용하려면 기본 세팅 필요
    // 요청.query : 유저가 보낸 URL query 데이터를 출력 가능 (query string)
    console.log(요청.body)

    // 예외 처리 (검열처리) => if/else문
    // 만약 제목이나 내용이 없다면 다시 작성하게끔 하기
    if (요청.body.title == '' || 요청.body.content == '') {
      // 다시 작성하라는 메세지와 함께 작성창 다시 로드하기
      응답.send("<script>alert('제목이나 내용이 없습니다. 다시 작성해주십시오.'); window.location.replace('/write');</script>");
    }

    else {
      // 만약에 db가 다운되거나 db가 용량이 딸릴때는 저장하면 안되지 않을까?
      // 에러상황 처리는 try, catch
      try {
        await db.collection('post').insertOne({
          title : 요청.body.title, // 제목 넣기
          content : 요청.body.content // 내용 넣기
        });
        // 다른 페이지로 이동시키기 : 응답.redirect
        응답.redirect ('/list');
      } catch (err) {
        console.log(err); // 에러 출력하기
        return 응답.status(500).send('server error occurred');
        // 500은 서버잘못으로 인한 에러라는 뜻임
      }
    }
});