반응형
01. 모듈생성
nest는 복사해서 먼가 모듈을 만드는게 아니라 터미널에 명령어를 친후 생성을 하는데
예시로 users라는 모듈을 만들고 싶다면 아래와 같이 치면 src폴더에 생성이 된다.
이렇게 하는게 자동으로 app쪽에 넣어줘서 좋음
// 모듈생성
nest g mo users
// 컨트롤러 생성
nest g co users
// 서비스 생성
nest g s users
02. nestjs/config
말그대로 환경설정을 하기 위한 것이고 dotenv도 어차피 모듈로 만들어야 하면 모듈로 만들어진 nestjs/config를 쓰는게 좋다
npm i --save @nestjs/config
https://docs.nestjs.com/techniques/configuration
03. morgen 대신 logger
nest버전의 morgen이라 생각하면 된다.
어느 부분이 잘못됫는지 어느 데이터가 들어왓는지를 알수있는 거다. 다 콘솔로그 찍을수는 없으니까.
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Response, Request } from 'express';
@Injectable()
// morgen
// implements - use를 강제로 만들어야 된다.
export class LoggerMiddelewate implements NestMiddleware {
// 다른함수들의 콘솔로그의 추적을 위해 작성
// 일종의 디버그
private logger = new Logger('http');
use(request: Request, response: Response, next: NextFunction): void {
const { ip, method, originalUrl } = request;
// user-agent - 브라우저 종류 버전 os 판별
const userAgent = request.get('user-agent') || '';
// 응답이 끝날시
response.on('finish', () => {
const { statusCode } = response;
const contentLength = response.get('content-length');
// 로그에 찍는데 순서는 메소드 url 상태코드 길이 아이피 등등
this.logger.log(
`메소드 : ${method} ${originalUrl} ${statusCode} ${contentLength} - ${userAgent} ip :${ip}`,
);
});
next();
}
}
04. 인터셉터
말그대로 중간에 가로채서 뭔가를 하는건데 이번에 만든거는 데이터가 언디파인드일때 null값을 주는 인터셉터다.
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class UndefinedToNullInterceptor implements NestInterceptor {
intercept(
context: ExecutionContext,
next: CallHandler,
): Observable<any> | Promise<Observable<any>> {
// 컨트롤러에 가기전 부분
return next
.handle()
.pipe(map((data) => (data === undefined ? null : data)));
}
}
05. typeorm
node에서는 시퀄라이즈를 사용햇는데 typeorm과의 차이점은 아래와 같다.
🚩 Sequelize 특징
- 유연성 : Sequelize의 폭넓은 호환성 덕분에 다양한 데이터베이스를 이용한 프로젝트에 많이 선택 됩니다.
- 활발한 생태계 : 다양한 문서와 대규모 커뮤니티를 통해 문제 해결을 위한 충분한 리소스를 찾을 수 있다.
- 원시 SQL 쿼리 : 원시 SQL이 필요한 경우 Sequelize를 사용하면, 쿼리를 직접 실행 시킬 수 있습니다.
🚩 TypeORM 특징
- TypeScript 통합 : TypeORM은 기본적으로 TypeScript를 수용하여 타이핑, 컴파일 타입 검사합니다.
- Decorators : 데코레이터를 사용하면 TypeScript 클래스에서 바로 엔터티와 관계를 정의 할 수 있습니다.
- 자동 마이그레이션 : TypeORM은 자동 마이그레이션을 제공해 데이터베이스 스키마 변경을 단순화합니다.
🚩 설치순서
- npm i typeorm-model-generator -D
- 데이터 베이스 생성 자세한 내용은 아래에
- npx typeorm-model-generator -h localhost -d db명 -u -root -x 비밀번호 -e db종류
- npm run db:create 데이터 베이스 생성 -> npm run start:dev -> 테이블 생성
// 순서 2번 내용임
// package.json에 넣는다.
// npm i typeorm-extension typeorm @nestjs/typeorm 설치
"db:create": "ts-node ./node_modules/typeorm-extension/bin/cli.cjs db:create -d ./dataSource.ts",
"db:drop": "ts-node ./node_modules/typeorm-extension/bin/cli.cjs db:drop -d ./dataSource.ts",
"seed": "ts-node ./node_modules/typeorm-extension/bin/cli.cjs seed -d ./dataSource.ts",
"schema:drop": "ts-node ./node_modules/typeorm/cli.js schema:drop",
"schema:sync": "ts-node ./node_modules/typeorm/cli.js schema:sync",
"db:migrate": "npm run typeorm migration:run -- -d ./dataSource.ts",
"db:migrate:revert": "npm run typeorm migration:revert -- -d ./dataSource.ts",
"db:create-migration": "npm run typeorm migration:create -- ./src/migrations/",
"db:generate-migration": "npm run typeorm migration:generate -- ./src/migrations -d ./dataSource.ts"
// app.module.ts
TypeOrmModule.forRoot({
// db타입
type: 'mysql',
host: 'localhost',
port: 3306,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
// 관계설정한거 넣기
entities: [
ChannelChats,
ChannelMembers,
Channels,
DMs,
Mentions,
Users,
WorkspaceMembers,
Workspaces,
],
keepConnectionAlive: true,
synchronize: true,
logging: true,
charset: 'utf8mb4_general_ci',
}),
TypeOrmModule.forFeature([Users]),
여기서 중요한거는 entities 즉 관계를 다짠다음에 작업을 해야한다.
반응형