[nodejs] Fastify 데이터베이스 통합

Fastify는 빠르고 효율적인 웹 프레임워크로서, 데이터베이스와의 통합을 통해 더 다양한 기능을 제공할 수 있습니다. 이번에는 Fastify와 데이터베이스를 연동해서 간단한 RESTful API를 만들어보겠습니다.

1. Fastify 플러그인 설치

Fastify에서는 다양한 데이터베이스를 지원하는 플러그인을 제공합니다. MongoDB를 사용하고자 한다면 fastify-mongodb 플러그인을 설치할 수 있습니다.

const fastify = require('fastify')();

fastify.register(require('fastify-mongodb'), {
  url: 'mongodb://localhost:27017/mydb'
});

fastify.listen(3000, (err) => {
  if (err) {
    console.error(err);
    process.exit(1);
  }
  console.log('Server listening on http://localhost:3000');
});

2. RESTful API 구현

이제 간단한 RESTful API를 구현해보겠습니다. 이 예제에서는 사용자를 추가하고 조회하는 두 가지 엔드포인트를 만들어보겠습니다.

fastify.post('/users', async (request, reply) => {
  const { name, email } = request.body;
  const result = await fastify.mongo.db.collection('users').insertOne({ name, email });
  reply.code(201).send(result.ops[0]);
});

fastify.get('/users', async (request, reply) => {
  const users = await fastify.mongo.db.collection('users').find().toArray();
  reply.send(users);
});

이제 POST /users 엔드포인트로 사용자를 추가하고, GET /users 엔드포인트로 사용자 목록을 조회할 수 있습니다.

3. 데이터베이스 연동 결과 확인

실제로 서버를 실행하고 RESTful API를 테스트해보겠습니다.

$ curl -X POST -H "Content-Type: application/json" -d '{"name":"Alice", "email":"alice@example.com"}' http://localhost:3000/users
$ curl http://localhost:3000/users

위 명령어를 통해 사용자를 추가하고 목록을 조회해볼 수 있습니다.

이처럼 Fastify와 데이터베이스를 연동하여 간단한 RESTful API를 빠르게 구현할 수 있으며, 실제 프로덕션 환경에서도 빠른 성능을 제공할 수 있습니다.

참고 자료