nestjs, typeorm 세팅

joDMSoluth·2020년 10월 22일
3

nestjs

목록 보기
1/1

유튜브 강의를 보고 따라 만든 프로젝트입니다.

세팅

1. nestjs 프로젝트 생성

# nestjs cli 설치
npm i -g @nestjs/cli
npx nest new task-management-api

만들어진 폴더로 이동해서 typeorm 세팅

# typeorm 설치
cd task-masnagement-api
npm install --save @nestjs/typeorm typeorm pg

참고 ) nestjs doc

2. Typeorm, Postgre 세팅

  • src/ormconfig.ts 파일을 만들어 준다.
import { ConnectionOptions } from 'typeorm';

// You can load you .env file here synchronously using dotenv package (not installed here),
// import * as dotenv from 'dotenv';
// import * as fs from 'fs';
// const environment = process.env.NODE_ENV || 'development';
// const data: any = dotenv.parse(fs.readFileSync(`${environment}.env`));
// You can also make a singleton service that load and expose the .env file content.
// ...


// Check typeORM documentation for more information.
const config: ConnectionOptions = {
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    username: 'postgres',
    password: '123456',
    database: 'task-management',
    entities: [__dirname + '/**/*.entity{.ts,.js}'],

    // We are using migrations, synchronize should be set to false.
    synchronize: false,

    // Run migrations automatically,
    // you can disable this if you prefer running migration manually.
    migrationsRun: false,
    logging: true,
    logger: 'file',

    // Allow both start:prod and start:dev to use migrations
    // __dirname is either dist or src folder, meaning either
    // the compiled js in prod or the ts in dev.
    migrations: [__dirname + '/migrations/**/*{.ts,.js}'],
    cli: {
        // Location of migration should be inside src folder
        // to be compiled into dist/ folder.
        migrationsDir: 'src/migrations',
    },
};

export = config
  • 그 다음 데이터 베이스 모듈을 생성해준다.
nest g module database

src/database/database.module.ts파일

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import * as ormconifg from '../ormconfig'

// ormconfig를 넣어준다.
@Module({imports: [TypeOrmModule.forRoot(ormconifg)]})
export class DatabaseModule {}
  • typeorm 마이그레이션(스키마 생성), run(테이블 생성)을 시작한다.
npm run typeorm migration:generate -- -n <migrationNameHere>
npm run typeorm migration:run
  • 테이블이 생성된다.
profile
풀스택이 되고 싶은 주니어 웹 개발자입니다.

0개의 댓글