자바스크립트 async/await를 이용한 데이터베이스 연동

지난 몇 년간 자바스크립트는 웹 애플리케이션 개발을 위한 주요한 언어로서 성장해 왔습니다. 하지만 이제는 클라이언트 측 뿐만 아니라 서버 측에서도 자바스크립트를 사용하여 데이터베이스와의 통신을 손쉽게 할 수 있게 되었습니다.

데이터베이스와의 비동기적인 상호작용은 이벤트 기반 프로그래밍을 필요로 하므로, 비동기적인 코드를 깔끔하고 직관적으로 작성하기 위해 자바스크립트에서 async/await 패턴을 사용할 수 있습니다. 이를 통해 데이터베이스와의 연동을 간소화하고 가독성을 높일 수 있습니다.

데이터베이스 연동의 기초

데이터베이스와의 연동을 위해 우리는 대부분의 경우에 데이터베이스 드라이버를 사용해야 합니다. 예를 들어, Node.js 환경에서는 MongoDB를 사용한다면 mongodb 패키지를 사용하여 데이터베이스에 연결하고 데이터를 조회, 추가, 수정 및 삭제할 수 있습니다.

async/await를 사용하는 데이터베이스 연동의 기초를 살펴보기 위해, 몇 가지 예시를 살펴보겠습니다.

MongoDB와의 연동

아래는 mongodb 패키지와 async/await를 사용하여 MongoDB와의 연동을 하는 간단한 예시입니다.

const { MongoClient } = require('mongodb');

async function connectToDatabase() {
  const url = 'mongodb://localhost/mydatabase';
  const client = new MongoClient(url);

  try {
    // 데이터베이스 연결
    await client.connect();
    console.log('Connected to the database');

    // 데이터 조회
    const db = client.db();
    const collection = db.collection('users');
    const users = await collection.find().toArray();
    console.log(users);

    // 데이터 삽입
    const newUserData = { name: 'John', age: 30 };
    await collection.insertOne(newUserData);
    console.log('Data inserted successfully');
  } catch (error) {
    console.error('Error connecting to the database:', error);
  } finally {
    // 연결 해제
    await client.close();
    console.log('Disconnected from the database');
  }
}

connectToDatabase();

위의 예시에서는 mongodb 패키지에서 제공되는 MongoClient를 사용하여 데이터베이스에 연결합니다. client.connect 메서드를 호출함으로써 연결을 시도하고, client.db를 호출하여 연결된 데이터베이스에 접근합니다.

그 후, collection.find 함수를 사용하여 데이터를 조회하고, collection.insertOne 함수로 데이터를 삽입합니다.

PostgreSQL과의 연동

데이터베이스와의 연동에는 MongoDB뿐만 아니라 다른 데이터베이스도 포함됩니다. PostgreSQL은 널리 사용되는 관계형 데이터베이스이며, pg 패키지는 PostgreSQL과의 연결을 제공합니다.

const { Client } = require('pg');

const client = new Client({
  user: 'yourUsername',
  password: 'yourPassword',
  host: 'localhost',
  database: 'yourDatabase',
  port: 5432,
});

async function connectToDatabase() {
  try {
    // 데이터베이스 연결
    await client.connect();
    console.log('Connected to the database');

    // 데이터 조회
    const res = await client.query('SELECT * FROM users');
    console.log(res.rows);

    // 데이터 삽입
    const newUserData = { name: 'Jane', age: 25 };
    await client.query('INSERT INTO users (name, age) VALUES ($1, $2)', [newUserData.name, newUserData.age]);
    console.log('Data inserted successfully');
  } catch (error) {
    console.error('Error connecting to the database:', error);
  } finally {
    // 연결 해제
    await client.end();
    console.log('Disconnected from the database');
  }
}

connectToDatabase();

위의 예시에서는 pg 패키지에서 제공되는 Client를 사용하여 PostgreSQL과의 연결을 생성합니다. client.connect 메서드를 호출하여 연결하고, client.query를 호출하여 데이터를 조회하고 삽입합니다.

마치며

자바스크립트 async/await를 사용하여 데이터베이스와의 연동을 효과적으로 처리할 수 있습니다. 비동기적인 작업을 동기적인 스타일로 작성할 수 있어 코드의 가독성을 높이고 유지보수를 용이하게 만들어 줍니다.

이러한 패턴은 데이터베이스와의 연동뿐만 아니라, HTTP 요청, 파일 시스템 액세스 등 다양한 비동기 작업에도 적용될 수 있습니다. async/await을 기반으로 하는 자바스크립트 프로그래밍은 단순함과 생산성을 제공하므로, 다양한 프로젝트에서 이를 적극적으로 활용해보시기 바랍니다.