반응형
01 . 설치 순서 (공문에 잇어용)
1. npm i -g @nestjs/cli
2. nest new project-name
02. hot-reload
node에 nodemon이 있다면 nest에 hot-reload가 있다라고 생각하면된다.
https://docs.nestjs.com/recipes/hot-reload 이대로 하면됨
$ npm i --save-dev webpack-node-externals run-script-webpack-plugin webpack
// webpack-hmr.config.js
const nodeExternals = require('webpack-node-externals');
const { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');
module.exports = function (options, webpack) {
return {
...options,
entry: ['webpack/hot/poll?100', options.entry],
externals: [
nodeExternals({
allowlist: ['webpack/hot/poll?100'],
}),
],
plugins: [
...options.plugins,
new webpack.HotModuleReplacementPlugin(),
new webpack.WatchIgnorePlugin({
paths: [/\.js$/, /\.d\.ts$/],
}),
new RunScriptWebpackPlugin({ name: options.output.filename, autoRestart: false }),
],
};
};
"start:dev": "nest build --webpack --webpackPath webpack-hmr.config.js --watch"
// main.ts
declare const module: any;
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => app.close());
}
}
bootstrap();
03. module
node와 다르게 nest는 모듈로 나눈다.
node는 router nest는 모듈
@Controller('abc')
export class AppController {
constructor(private readonly appService: AppService) {}
@Get() // Get
getHello(): string {
return this.appService.getHello();
}
@Post() // post
postHello(): string {
return this.appService.getHello();
}
}
04. 모듈생성
nest는 복사해서 먼가 모듈을 만드는게 아니라 터미널에 명령어를 친후 생성을 하는데 예시로 users라는 모듈을 만들고 싶다면 아래와 같이 치면 src폴더에 생성이 된다. 이렇게 하는게 자동으로 app쪽에 넣어줘서 좋음
// 모듈생성
nest g mo users
// 컨트롤러 생성
nest g co users
// 서비스 생성
nest g s users
05. no nestjs/config
말그대로 환경설정을 하기 위한 것이고 dotenv도 어차피 모듈로 만들어야 하면 모듈로 만들어진 nestjs/config를 쓰는게 좋다
npm i --save @nestjs/config
https://docs.nestjs.com/techniques/configuration
06. logger 미들웨어
morgan 같은거임.
// middlewares/logger.middleware.ts
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
@Injectable()
// morgen
// implements - use를 강제로 만들어야 된다.
export class LoggerMiddelware implements NestMiddleware {
private logger = new Logger('http');
use(req: Request, res: Response, next: NextFunction): void {
const { ip, method, originalUrl } = req;
// user-agent - 브라우저 종류 버전 os 판별
const userAgent = req.get('user-agent') || '';
res.on('finish', () => {
const { statusCode } = res;
const contentLength = res.get('content-length');
this.logger.log(
`${method} ${originalUrl} ${statusCode} ${contentLength} - ${userAgent} ${ip}`,
);
});
next();
}
}
// app.module.ts
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddelware).forRoutes('*');
}
}
반응형