Node.js

TypeORM + TypeScript + Express 개발환경 세팅

후뿡이 2023. 7. 3. 17:27

 

1. TypeORM 세팅 


TypeORM, TypeScript, Express 를 이용한 개발환경을 세팅하려고 한다.

 

먼저 여러가지 시도를 해 본 결과 

TypeScript + Express를 먼저 세팅하는게 아니라

TypeORM을 먼저 세팅하는게 좋을 것 같다고 판단했다.

 

왜냐하면 TypeORM init 해주면 아래의 directory 들이 자동으로 생성되는데 이 때 이미 Typescript가 설정되어 있는 상태로 설치가 진행되기 때문에 따로 Typescript를 설치해 줄 필요가 없기 때문이다 !

 

TypeORM 홈페이지의 디렉토리 설명

 

 

자동으로 생성된 pakage.json file을 살펴보면 더 자세히 이해할 수 있다.

typeorm init 을 통해 자동 생성된 pakage.json file

생성된 pakage.json file 안에 이미 typescript 모듈과 node에서 typescript를 사용하기 위해 필요한 @types/node와 ts-node가 설치되어 있음을 확인할 수 있다.

이렇듯 먼저 typeORM을 설정해 주면 간편하게 typescript까지 설치해 줄 수 있다 !

 

npx typeorm init --name MyProject --database database-you-want-to-use

typeorm은 위의 명령어를 통해 간단하게 시작할 수 있다.

 

 

설치 후 src/index.ts파일을 살펴보자

import { AppDataSource } from "./data-source"
import { User } from "./entity/User"


AppDataSource.initialize().then(async () => {

    console.log("Inserting a new user into the database...")
    const user = new User()
    user.firstName = "Timber"
    user.lastName = "Saw"
    user.age = 25
    await AppDataSource.manager.save(user)
    console.log("Saved a new user with id: " + user.id)

    console.log("Loading users from the database...")
    const users = await AppDataSource.manager.find(User)
    console.log("Loaded users: ", users)


	#이곳에서 다양한 프레임워크를 실행할 수 있다고 한다.
    console.log("Here you can setup and run express / fastify / any other framework.")
    


}).catch(error => console.log(error))

 

마지막 console.log를 확인해 보면 자동생성된 index.ts 에서 다양한 프레임워크를 실행할 수 있다고 한다.

 

그렇다면 그 다음에 우리가 사용하려는 express를 설치해 보자

 

2. Express 세팅 


먼저 Express 를 사용해 주기 위해서는 express module을 설치해줘야 한다.

npm i express
npm i -D @types/express

 

위의 두 명령어를 실행해 주자

@types/express 모듈같은 경우 express는 자바스크립트 기반으로 되어있기 때문에 express를 typescript 기반으로 사용하기 위해서 필요한 모듈이다. 이 모듈의 경우 개발환경에서만 필요하기 때문에 -D 를 붙여 devDependencies에 추가해 준다.

 

pakage.json file을 확인해 보면 다음과 같다.

express, @types/express 모듈이 정상적으로 설치된 것을 확인할 수 있다.

두 개 이외의 모듈들은 npx typeorm init 을 통해 설치된 모듈들이다.

 

설치 후에 indes.ts file에 express 서버를 시작하는 코드를 작성해 주자.

 

# src/index.ts

import { AppDataSource } from "./data-source"
import { Request, Response } from "express"
import * as express from 'express'

// database connection
AppDataSource
    .initialize()
    .then(async () => {
        console.log("Data Source has been initialized")
        })
    .catch(error => console.log(error))

// create and setup express app
const app = express();
const port = 2220;
app.use(express.json())

app.get('/',(req:Request,res:Response) => {
    res.send('Hello World')
})

// start express server
app.listen(port, () => {
    console.log('######################################')
    console.log(`##### server is running on ${port} ######`)
    console.log('######################################')
})

 

필요 없는 테스트 코드를 지워준 후 위와 같이 express를 시작하는 코드를 작성했다.

서버를 실행해 보자 !

 

 

3. Database 세팅 


error: role "test" does not exist

서버를 실행해 보니 위와 같은 에러가 발생했다. 이는 TypeORM의 경우 Database와 연결해 주어야 하는데 DB 설정을 변경하지 않았기 때문에 발생하는 에러이다. 

src/data-source.ts file에서 DB 설정을 확인해 보자

# src/data-source.ts

import "reflect-metadata"
import { DataSource } from "typeorm"
import { User } from "./entity/User"

export const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "test",
    database: "test",
    synchronize: true,
    logging: false,
    entities: [User],
    migrations: [],
    subscribers: [],
})

 

DB 접속을 위한 설정이 전부 기본으로 설정되어 있는 모습이다.

사용할 database를 생성해준 후 설정을 바꾸어 주자

 

나는 아래와 같이 설정했다.

유저는 기본 유저인 postgres를 사용했고

database의 경우 couplediary database를 생성해 주었다.

 

# src/data-source.ts

import "reflect-metadata"
import { DataSource } from "typeorm"
import { User } from "./entity/User"

export const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "postgres",
    password: "postgres",
    database: "couplediary",
    synchronize: true,
    logging: false,
    entities: [User],
    migrations: [],
    subscribers: [],
})

 

 

4. 실행 결과


 

서버가 정상적으로 동작함을 확인할 수 있었다.

위의 방법으로 TypeORM + TypeScript + Express 을 사용한 프로젝틀 설정을 할 수 있다.

 

 

 

잘못된 내용이 있으면 언제든지 댓글 부탁드립니다.

 

출처