node js express js를 활용한 Rest api구현하기

활동하는 소모임에서 todos 역할을 하는 간단한 rest api기능을 구현하는 미션을 받았다.

rest api란 이제 백엔드 서버를 다루는데 있어서, 프론트엔드 부분에서 데이터의 request와 response의 상호작용을 위한 하나의 규칙이라고 보면 될 것 같다. 뭐 데이터를 주고 받으려면 이제 DB에서 읽어오면 될 것인데 이제 DB를 사용하기 위한 기능이 무엇이 있는지 생각해보자.

  1. 읽기
  2. 쓰기
  3. 수정
  4. 삭제

DB를 조작하기 위해 가장 기초적으로 배우는 이 4가지가 있을 것이다. 여기까지 설명을 토대로 이해하기 쉽게 한마디로 정리해보면 rest api의 가장 중요한 기능은 DB의 데이터와 상호작용하는 4가지 기능을 구현하기 위한 규칙이라고 보면 된다.

나는 구현하기 전까지도 rest api에 대한 문서만 읽으면서 이해하는게 너무 어려웠는데 진작 구현부터 해보면서 부딪혀볼걸 그랬다..

그러면 가장 흔히 알려진 프레임워크중 하나인 node js express js 와 기능을 테스트해보는 도구로 포스트맨을 사용하여 rest api를 구현하여 보자.

참고로 아직 처음 구현하는 것인만큼 DB의 데이터를 읽는 것이 아닌 JSON파일을 읽고쓰면서 단순하게 적용해보았다. 근데 DB를 사용할 줄 안다면 DB로 바로 시작하는게 어쩌면 이해하기 쉽고 단순할 수도 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const fs = require('fs');
var dbFile = 'db.json';
var dbDataBuffer = fs.readFileSync(dbFile);
var dbJSON = dbDataBuffer.toString();

const express = require('express');
const { captureRejectionSymbol } = require('events');
const { type } = require('os');
const e = require('express');
const app = express();
const PORT = 5000;
app.use(express.json());
app.get('/', (req, res) => {
	console.log('GET\t/');
	res.send('HELLo World!');
});

/*
 **	GET /todos/
 */

app.get('/todos/', (req, res) => {
	console.log('GET\t/todos/');
	//  dbJSON.success = true;
	try {
		res.json(dbJSON);
	} catch (e) {
		console.log('err');
	}
});

/*
 ** POST /todos/
 */

app.post('/todos/', (req, res) => {
	console.log('POST\t/todos/');
	try {
		const todo = req.body;
		var arr = new Array();
		var temp = JSON.parse(dbJSON).todos;
		arr = temp;
		arr.push(todo);
		const result = JSON.parse(dbJSON);
		result.todos = arr;
		var dataJson = JSON.stringify(result);
		fs.writeFileSync(dbFile, dataJson);
		res.send('success');
	} catch (e) {
		console.log(e);
	}
	console.log(req.body);
	console.log(dataJson);
});

/*
 **	PATCH /todos/:todo_id
 */

app.patch('/todos/:todo_id', (req, res) => {
	console.log('PATCH\t/todos/');
	try {
		var id = req.params.todo_id;
		var data = JSON.parse(dbJSON);
		for (var i = 0; i < data.todos.length; i++) {
			if (data.todos[i].id === Number(id)) {
				data.todos[i] = req.body;
				break;
			}
			if (i === data.todos.length - 1) {
				throw e;
			}
		}
		var dataJson = JSON.stringify(data);
		fs.writeFileSync(dbFile, dataJson);
		res.send('success');
	} catch (e) {
		res.send('fail');
		console.log("don't find data");
	}
});

/*
 **	DELETE /todos/:todo_id
 */

app.delete('/todos/:todo_id', (req, res) => {
	console.log('DELETE\t/todos/');
	try {
		var id = req.params.todo_id;
		var data = JSON.parse(dbJSON);
		for (var i = 0; i < data.todos.length; i++) {
			if (data.todos[i].id === Number(id)) {
				data.todos.splice(i, 1);
				break;
			}
			if (i === data.todos.length - 1) {
				throw e;
			}
		}
		var dataJson = JSON.stringify(data);
		fs.writeFileSync(dbFile, dataJson);
		res.send('success');
	} catch (e) {
		res.send('fail');
		console.log("don't find data");
	}
});

app.listen(PORT, () => {
	console.log('Something behind... you have to implement this...!');
	console.log(`Server is running and listening on port ${PORT}!`);
});

아무래도 모든 기능은 구현이 되지만 json파일을 업데이트 할 때 마다 처음부터 다시 쓰기 때문에 비효율적인 코드일 수 있다. 이 부분을 수정해야하고, node js의 특성인 동기, 비동기에 대해 학습해서 이것 또한 적용해봐야 겠다.