Backend/Node.js

Node.js - Express.js와 REST API (2)

yxemsy 2022. 2. 20. 21:54

< Express.js로 REST API 구현하기 >

  • 자바스크립트의 Array 함수 사용하여 데이터 처리 구현
  • router와 route handler 사용해 HTTP요청, 응답 처리 구현

(1) 메모 목록 구현하기 

- models/note.js 

note라는 모델을 모듈로 선언

let notes = [			// 데이터들
   { 
    id: 1, 
    title: 'first note', 
    content: 'My first note'
    }
];

exports.list= () => { 	// list를 내보내기 위한 exports
	return notes.map(({ id, title }) => ({ 
        id, 
    	title,
        }))
 }

map이라는 배열 함수를 사용하여 { id, title }를 하나씩 순회하여 받아옴

 

- routes/notes.js

const { Router } = require('express');
const Note = require('../models/note'); // models 폴더의 note.js에서 exports한 list를 가져오기 위함

const router = Router(); // Router 객체 생성

router.get('/', (req, res, next) => {  // list를 가져오기 위한 HTTP method
    const notes = Note.list(); // notes는 note.js의 list
    res.json(notes); // notes를 json 형식으로 응답
});

 


(2) 메모 상세 구현하기 (이전의 메모 목록 구현하기에 누적된 코드 즉, exports 되어있다고 생각하기)

- models/note.js

exports.get = (id) => {			// routes의 notes.js의 get 함수에서 id 인자로 보내주면 받아와서
     const note = notes.find(	
     	(note) => note.id === id  // 전달받은 id 값의 note를 가져온다.
    );
    
    if(!note) { 
    	throw new Error('Note not found'); // 만약 id가 없으면 던질 에러
     }
     return note; // 찾은 값이 있으면 note를 return
 }

find()라는 배열 함수는 notes 목록을 돌면서 note.id === id가 참인 것을 return 해준다.

 

- routes/notes.js

router.get('/:id', (req, res, next) => {
    const id = Number(req.params.id);	 // params를 이용해 html의 form 태그에서 id 값을 받아온다.
    
    try{
    	const note = Note.get(id); // models의 note.js의 get 함수에 id 값을 넣어 실행한 결과 반환 
        res.json(note);			// note를 json 형태로 표현
        } catch(e) {
        	next(e);	// models의 note.js에서 if(!note)일 때 throw new Error가 반환됨
        }
     });

'/:id'를 통해 path parameter로 id를 받도록 하였다. 기본적으로 입력받은 값은 string이라서 Number()함수를 사용해

id를 정수로 바꾸어준다.

 


(3) 메모 작성 구현하기

- models/note.js

exports.create = (title, content) => {
    const { id: lastId } = 		// id가 배열의 길이 -1 이라는 건 제일 마지막 id라는 것
    	notes[notes.length - 1];
    const newNote= { 
    	id: lastId + 1,  // 새로 작성된 노트는 마지막 아이디에 +1 한 id를 부여
        title, 			// routes/notes.js에서 받은 title과 content를 담음
        content,
    };
    
    notes.push(newNote);
    return newNote; // 생성된 newNote를 반환
 }

push() 함수를 사용하면 notes의 가장 마지막 배열로 newNote 를 추가해준다.

 

- routes/notes.js

router.post('/', (req, res, next) => {
    const { title, content } = req.body; // title, content에 요청된 각 값을 req.body로 가져옴
    const note = Note.create(title, content); // models/note.js의 create함수 실행
    res.json(note);
})

 


 

(4) 메모 수정 구현하기

- models/note.js

exports.update = (id, title, content) => { 
    const index = notes.findIndex(    // findIndex는 인덱스값을 반환
    	(note) => note.id === id		// 전달받은 id의 note에 해당하는 값을 찾음
        );
        
        if(index < 0) {
        	throw new Error('Note not found for update'); // 해당 id가 없으면 에러 던짐
        }
        const note = notes[index]; // 요소를 객체로 전달받음.
        note.title = title;			// 이 객체에 새로 입력받은 title로 변경
        note.content = content;		// 새로 입력받은 content로 변경
        notes[index] = note;		// 변경된 note로 notes[index] 수정
        return note;				// 변경된 note return
     }

findIndex()함수는 조건에 맞는 요소가 찾아졌을 때 조건의 인덱스를 반환해준다.

인덱스가 0보다 작은 것은, 해당하는 요소가 없다는 것이다.

 

- routes/notes.js

router.put('/:id', (req, res, next)=> { 
    const id = Number(req.params.id);
    const { title, content } = req.body;
    
    try { 
    	const note = 
        	Note.update(id, title, content); // note.js의 update 함수로 인자 전달
        res.json(note);
     } catch(e) {
     	next(e);
        }
   });

 


(5) 메모 삭제 구현하기

- models/note.js

exports.delete = (id) => {
    if (!notes.some((note) => note.id === id)) {  // 전달받은 id에 해당하는 note가 없다면 오류
    	throw new Error('Note not found for delete');
    }
    
    notes = notes.filter(note => note.id !== id);
    return;  // 삭제는 반환 값 필요없음
}

some()함수는 특정 조건에 맞는 요소가 있는지를 찾는다. 반환 값은 true나 false다

filter()함수는 조건에 해당하는 참인 값을 남기는 것이다. 즉, 노트에 전달된 아이디와 다른 아이디만을 남긴다.

 

- routes/notes.js

router.delete('/:id', (req, res, next) => {
    const id = Number(req.params.id);
    
    try{
    	Note.delete(id);		// id를 note.js의 delete 함수에 전달
        res.json({ result: 'success' });
        } catch(e) {
        	next(e);
       }
    });

 

* 우리는 res.json()을 통해 json 형식의 데이터를 전달하려고 했다. 이 때 필요한 미들웨어가 있다.

app.use(express.json())

이 미들웨어를 app에 연결해주어야 json 데이터를 사용할 수 있다.