노드서버 DB 연결하기 / Dwitter DB 연동

1. Mysql 다운로드

운영체제에 맞는 mysql 서버, workbench 를 다운로드 받고, db 스키마를 작성 / 테이블을 생성한다.

2. mysql2 다운로드

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm i mysql2
npm i mysql2
npm i mysql2 

3. 노드서버 <> DB 연결

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { config } from "../config.js";
import mysql from "mysql2";
const pool = mysql.createPool({
host: config.db.host,
user: config.db.user,
database: config.db.database,
password: config.db.password,
port: config.db.port,
});
export const db = pool.promise(); // 비동기 db 호출
import { config } from "../config.js"; import mysql from "mysql2"; const pool = mysql.createPool({ host: config.db.host, user: config.db.user, database: config.db.database, password: config.db.password, port: config.db.port, }); export const db = pool.promise(); // 비동기 db 호출
import { config } from "../config.js";
import mysql from "mysql2";

const pool = mysql.createPool({
  host: config.db.host,
  user: config.db.user,
  database: config.db.database,
  password: config.db.password,
  port: config.db.port,
});

export const db = pool.promise(); // 비동기 db 호출
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import dotenv from "dotenv";
dotenv.config();
function required(key, defaultValue = undefined) {
const value = process.env[key] || defaultValue;
if (value == null) {
throw new Error(`Key ${key} is undefined`);
}
return value;
}
export const config = {
jwt: {
secretKey: required("JWT_SECRET"),
expiresInSec: required("JWT_EXPIRES_SEC", 86400),
},
bcrypt: {
saltRounds: required("BCRYPT_SALT_ROUNDS", 12),
},
host: {
port: required("HOST_PORT", 8080),
},
db: {
host: required("DB_HOST"),
user: required("DB_USER"),
database: required("DB_DATABASE"),
password: required("DB_PASSWORD"),
port: required("DB_PORT"),
},
};
import dotenv from "dotenv"; dotenv.config(); function required(key, defaultValue = undefined) { const value = process.env[key] || defaultValue; if (value == null) { throw new Error(`Key ${key} is undefined`); } return value; } export const config = { jwt: { secretKey: required("JWT_SECRET"), expiresInSec: required("JWT_EXPIRES_SEC", 86400), }, bcrypt: { saltRounds: required("BCRYPT_SALT_ROUNDS", 12), }, host: { port: required("HOST_PORT", 8080), }, db: { host: required("DB_HOST"), user: required("DB_USER"), database: required("DB_DATABASE"), password: required("DB_PASSWORD"), port: required("DB_PORT"), }, };
import dotenv from "dotenv";
dotenv.config();

function required(key, defaultValue = undefined) {
  const value = process.env[key] || defaultValue;
  if (value == null) {
    throw new Error(`Key ${key} is undefined`);
  }
  return value;
}

export const config = {
  jwt: {
    secretKey: required("JWT_SECRET"),
    expiresInSec: required("JWT_EXPIRES_SEC", 86400),
  },
  bcrypt: {
    saltRounds: required("BCRYPT_SALT_ROUNDS", 12),
  },
  host: {
    port: required("HOST_PORT", 8080),
  },

  db: {
    host: required("DB_HOST"),
    user: required("DB_USER"),
    database: required("DB_DATABASE"),
    password: required("DB_PASSWORD"),
    port: required("DB_PORT"),
  },
};

(dotenv 를 이용하여 config 를 따로 분리하여 진행한다)

4. DB 연결 확인

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// app.js
import { db } from "./db/database.js";
db.getConnection().then(console.log);
// app.js import { db } from "./db/database.js"; db.getConnection().then(console.log);
// app.js
import { db } from "./db/database.js";

db.getConnection().then(console.log);

5. Dwitter 유저 테이블 연결

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// auth.js
import { db } from "../db/database.js";
export async function findByUsername(username) {
return db
.execute("SELECT * FROM users WHERE username=?", [username])
.then((result) => result[0][0]);
}
export async function findById(id) {
return db
.execute("SELECT * FROM users WHERE id=?", [id])
.then((result) => result[0][0]);
}
export async function createUser(user) {
const { username, password, name, email, url } = user;
return db
.execute(
"INSERT INTO users (username, password, name, email, url) VALUES (?,?,?,?,?)",
[username, password, name, email, url]
)
.then((result) => {
result[0].insertId;
});
}
// auth.js import { db } from "../db/database.js"; export async function findByUsername(username) { return db .execute("SELECT * FROM users WHERE username=?", [username]) .then((result) => result[0][0]); } export async function findById(id) { return db .execute("SELECT * FROM users WHERE id=?", [id]) .then((result) => result[0][0]); } export async function createUser(user) { const { username, password, name, email, url } = user; return db .execute( "INSERT INTO users (username, password, name, email, url) VALUES (?,?,?,?,?)", [username, password, name, email, url] ) .then((result) => { result[0].insertId; }); }
// auth.js

import { db } from "../db/database.js";

export async function findByUsername(username) {
  return db
    .execute("SELECT * FROM users WHERE username=?", [username])
    .then((result) => result[0][0]);
}

export async function findById(id) {
  return db
    .execute("SELECT * FROM users WHERE id=?", [id])
    .then((result) => result[0][0]);
}

export async function createUser(user) {
  const { username, password, name, email, url } = user;
  return db
    .execute(
      "INSERT INTO users (username, password, name, email, url) VALUES (?,?,?,?,?)",
      [username, password, name, email, url]
    )
    .then((result) => {
      result[0].insertId;
    });
}

6. Dwitter tweets 테이블 연결

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//tweet.js
import { db } from "../db/database.js";
const SELECT_JOIN =
"SELECT tw.id, tw.text, tw.createdAt, tw.userId, us.username, us.name, us.url FROM tweets as tw JOIN users as us ON tw.userId=us.id";
const ORDER_DESC = "ORDER BY tw.createdAt DESC";
export async function getAll() {
return db.execute(`${SELECT_JOIN} ${ORDER_DESC}`).then((result) => result[0]);
}
export async function getAllByUsername(username) {
return db
.execute(`${SELECT_JOIN} WHERE username=? ${ORDER_DESC}`, [username])
.then((result) => result[0]);
}
export async function getById(id) {
return db
.execute(`${SELECT_JOIN} WHERE tw.id=?`, [id])
.then((result) => result[0][0]);
}
export async function create(text, userId) {
return db
.execute("INSERT INTO tweets (text, createdAt, userId) VALUES (?,?,?)", [
text,
new Date(),
userId,
])
.then((result) => getById(result[0].insertId));
}
export async function update(id, text) {
return db
.execute("UPDATE tweets SET text=? WHERE id=?", [text, id])
.then(() => getById(id));
}
export async function remove(id) {
return db.execute("DELETE FROM tweets WHERE id=?", [id]);
}
//tweet.js import { db } from "../db/database.js"; const SELECT_JOIN = "SELECT tw.id, tw.text, tw.createdAt, tw.userId, us.username, us.name, us.url FROM tweets as tw JOIN users as us ON tw.userId=us.id"; const ORDER_DESC = "ORDER BY tw.createdAt DESC"; export async function getAll() { return db.execute(`${SELECT_JOIN} ${ORDER_DESC}`).then((result) => result[0]); } export async function getAllByUsername(username) { return db .execute(`${SELECT_JOIN} WHERE username=? ${ORDER_DESC}`, [username]) .then((result) => result[0]); } export async function getById(id) { return db .execute(`${SELECT_JOIN} WHERE tw.id=?`, [id]) .then((result) => result[0][0]); } export async function create(text, userId) { return db .execute("INSERT INTO tweets (text, createdAt, userId) VALUES (?,?,?)", [ text, new Date(), userId, ]) .then((result) => getById(result[0].insertId)); } export async function update(id, text) { return db .execute("UPDATE tweets SET text=? WHERE id=?", [text, id]) .then(() => getById(id)); } export async function remove(id) { return db.execute("DELETE FROM tweets WHERE id=?", [id]); }
//tweet.js

import { db } from "../db/database.js";

const SELECT_JOIN =
  "SELECT tw.id, tw.text, tw.createdAt, tw.userId, us.username, us.name, us.url FROM tweets as tw JOIN users as us ON tw.userId=us.id";
const ORDER_DESC = "ORDER BY tw.createdAt DESC";
export async function getAll() {
  return db.execute(`${SELECT_JOIN} ${ORDER_DESC}`).then((result) => result[0]);
}

export async function getAllByUsername(username) {
  return db
    .execute(`${SELECT_JOIN} WHERE username=? ${ORDER_DESC}`, [username])
    .then((result) => result[0]);
}

export async function getById(id) {
  return db
    .execute(`${SELECT_JOIN} WHERE tw.id=?`, [id])
    .then((result) => result[0][0]);
}

export async function create(text, userId) {
  return db
    .execute("INSERT INTO tweets (text, createdAt, userId) VALUES (?,?,?)", [
      text,
      new Date(),
      userId,
    ])
    .then((result) => getById(result[0].insertId));
}

export async function update(id, text) {
  return db
    .execute("UPDATE tweets SET text=? WHERE id=?", [text, id])
    .then(() => getById(id));
}

export async function remove(id) {
  return db.execute("DELETE FROM tweets WHERE id=?", [id]);
}