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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
| const fastify = require('fastify')({
logger: {
level: 'info',
prettyPrint: true
}
});
// JSON 스키마 정의
const userSchema = {
type: 'object',
properties: {
id: { type: 'integer' },
name: { type: 'string' },
email: { type: 'string', format: 'email' }
},
required: ['name', 'email']
};
// 사용자 데이터 저장소
const users = new Map();
// 플러그인 정의
const usersPlugin = async (fastify, options) => {
// CREATE
fastify.post('/users', {
schema: {
body: userSchema,
response: {
201: userSchema
}
}
}, async (request, reply) => {
const { name, email } = request.body;
const id = users.size + 1;
const user = { id, name, email };
users.set(id, user);
reply.code(201);
return user;
});
// READ
fastify.get('/users/:id', {
schema: {
params: {
type: 'object',
properties: {
id: { type: 'string' }
}
},
response: {
200: userSchema,
404: {
type: 'object',
properties: {
message: { type: 'string' }
}
}
}
}
}, async (request, reply) => {
const id = parseInt(request.params.id);
const user = users.get(id);
if (!user) {
reply.code(404);
return { message: 'User not found' };
}
return user;
});
// UPDATE
fastify.put('/users/:id', {
schema: {
params: {
type: 'object',
properties: {
id: { type: 'string' }
}
},
body: userSchema,
response: {
200: userSchema
}
}
}, async (request, reply) => {
const id = parseInt(request.params.id);
const { name, email } = request.body;
if (!users.has(id)) {
reply.code(404);
return { message: 'User not found' };
}
const user = { id, name, email };
users.set(id, user);
return user;
});
// DELETE
fastify.delete('/users/:id', {
schema: {
params: {
type: 'object',
properties: {
id: { type: 'string' }
}
}
}
}, async (request, reply) => {
const id = parseInt(request.params.id);
if (!users.has(id)) {
reply.code(404);
return { message: 'User not found' };
}
users.delete(id);
reply.code(204);
});
};
// 훅 사용 예시
fastify.addHook('preHandler', async (request, reply) => {
// 요청 처리 전에 실행되는 코드
request.log.info(`Incoming ${request.method} request to ${request.url}`);
});
// 플러그인 등록
fastify.register(usersPlugin);
// 커스텀 에러 핸들러
fastify.setErrorHandler((error, request, reply) => {
request.log.error(error);
reply.status(500).send({ error: 'Something went wrong' });
});
// 데코레이터 추가
fastify.decorateRequest('timestamp', null);
fastify.addHook('onRequest', async (request) => {
request.timestamp = new Date();
});
// 서버 시작
const start = async () => {
try {
await fastify.listen({ port: 3000 });
fastify.log.info(`Server listening on ${fastify.server.address().port}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
|