들어가며

이번 챕터에서도 9주차 워크북을 TS로 옮기는 내용이 주가 될 거에요.

깃헙으로 버전관리랑 이슈트래킹하는건 언어랑 관계 없이 똑같으니까 넘어가도록 할게요.

이번주도 바로 시작해보죠!

DB 연결

ORM과 SQL

코드에서 DB를 이용하는 방법은 크게 두가지로 나눌 수 있어요.

하나는 해당 DB 커넥터 라이브러리를 이용해서 SQL을 통해서 테이터를 주고받는 방법이고,

두번째는 ORM이라는, 더 추상화되서 SQL이 아니라 소스코드의 형태로 데이터를 주고받는 방법이죠.

첫번째 방법으로 수도코드로 짜보면 다음과 같은 형태가 되죠.

import { SomeDbConfig, initDb } from "some-db"
import { TargetEntity } from "./entities";

const config: SomeDbConfig = {
	host: "localhost",
	port: 3306,
	username: "user",
	password: "somePassWord"
};

const connectionPool = await initDb(config);
const connection = await connectionPool.getConnection();

// SQL을 직접 만들어줘야함
// SQL을 만드는 방식에 따라 SQL Injection 등의 보안 문제가 발생할수도 있음
const rawResult: Map<string, any>[] = 
		await connection.query("SELECT * FROM SOME_TABLE WHERE col1 > 1");

const result = rawResult.map((raw) => {
	const entity: Partial<TargetEntity> = {};
	entity.col1 = raw["col1"];
	entity.col2 = raw["col2"];
	
	return entity as TargetEntity;
});

// do something with result

반면 ORM을 이용하면?

import { SomeDbConfig, initDb, gt } from "awesome-orm";
import { TargetEntity } from "./entities";

const config: SomeDbConfig = {
	type: "some-db",
  host: "localhost",
	port: 3306,
	username: "user",
	password: "somePassWord",
	entities: [ TargetEntity ]
};

const db = await initDb(config);

const repo = db.getRepository(TargetEntity);

// 이런식으로 코드를 작성하면 ORM 라이브러리가 자동으로 SQL로 변환해서 데이터를 가져옴
const result: TargetEntity[] = repo.findMany({
	where: {
		col1: gt(1)
	}
});

// do something with result