ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • NestJS에서 프로젝트 기본 세팅 및 사용하는 라이브러리 정리
    Nest.js 2023. 8. 8. 11:18
    728x90

    NestJS 프로젝트 생성하기.

    $ nest new project-name --strict

     

    ts.config

    {
    	"compilerOptions": {
    		"module": "commonjs",
    		"declaration": true,
    		"removeComments": true,
    		"emitDecoratorMetadata": true,
    		"experimentalDecorators": true,
    		"allowSyntheticDefaultImports": true,
    		"target": "ES2021",
    		"sourceMap": true,
    		"outDir": "./dist",
    		"incremental": true,
    		"strict": true,
    		"skipLibCheck": true,
    		"strictNullChecks": true,
    		"strictBindCallApply": true,
    		"forceConsistentCasingInFileNames": true,
    		"noImplicitAny": true,
    		"noFallthroughCasesInSwitch": true,
    		"baseUrl": "./",
    		"esModuleInterop": true, // 추가
    		"paths": {
    			"@/*": ["src/*"],
    			"test/*": ["test/*"]
    		}
    	}
    }

    esModuleInterop 무조건 true 이거 때문에 nodemodule 다 지우고 해보고 난리도 아니였다

    prettier

    {
    	"trailingComma": "all",
    	"tabWidth": 2,
    	"useTabs": true,
    	"semi": true,
    	"singleQuote": true
    }

     

    esLint

    module.exports = {
    	parser: '@typescript-eslint/parser',
    	parserOptions: {
    		project: 'tsconfig.json',
    		tsconfigRootDir: __dirname,
    		sourceType: 'module',
    	},
    	settings: {
    		'import/resolver': {
    			typescript: {
    				project: './tsconfig.json',
    			},
    		},
    	},
    	plugins: ['@typescript-eslint/eslint-plugin', 'import'],
    	extends: [
    		'plugin:@typescript-eslint/recommended',
    		'plugin:prettier/recommended',
    	],
    	root: true,
    	env: {
    		node: true,
    		jest: true,
    	},
    	ignorePatterns: ['.eslintrc.js'],
    	rules: {
    		'@typescript-eslint/interface-name-prefix': 'off',
    		'@typescript-eslint/explicit-function-return-type': 'off',
    		'@typescript-eslint/explicit-module-boundary-types': 'off',
    		'@typescript-eslint/no-explicit-any': 'off',
    		'prettier/prettier': ['error', { endOfLine: 'auto' }],
    		'import/no-unresolved': 'error',
    		'import/order': [
    			'error',
    			{
    				groups: [
    					'builtin',
    					'external',
    					'internal',
    					['sibling', 'parent'],
    					'index',
    					'unknown',
    				],
    				'newlines-between': 'always',
    				alphabetize: {
    					order: 'asc',
    					caseInsensitive: true,
    				},
    			},
    		],
    	},
    };

     

     

    Configuration

    $ npm i --save @nestjs/config
    • 환경 변수 설정을 위해 설치합니다.

     

    cross-env

    $ npm install cross-env
    • 모든 운영체제에서 동일한 방법으로 환경 변수를 변경할 수 있게 된다.

     

    class-transformer

    $ npm install class-transformer

     

    class-validator

    $ npm install class-validator

     

    Cookie-parser

    $ npm install cookie-parser
    $ npm install -D @types/cookie-parser
    • cookie 정보를 가져오기 위해서 사용.

     

    bcryptjs

    $ npm install bcryptjs
    $ npm install -D @types/bcryptjs
    • 비밀번호 암호화 및 회원가입 인증 코드 암호화 등 암호화 작업에 사용.

     

    uuid

    $ npm install uuid
    $ npm install -D @types/uuid
    • Pk 설정의 uuid를 생성을 위해서.

    Logging

    $ npm install nest-winston winston

    https://www.npmjs.com/package/nest-winston

     

    nest-winston

    A Nest module wrapper for winston. Latest version: 1.9.3, last published: 2 months ago. Start using nest-winston in your project by running `npm i nest-winston`. There are 217 other projects in the npm registry using nest-winston.

    www.npmjs.com

     

    [Database]

    typeorm

    $ npm install --save @nestjs/typeorm typeorm pg
    • database typeorm 설치와, postgresql이면 pg를 설치 mysql사용이면 mysql2등 필요한 모듈 설치.

     

    [Auth]

    passport / @nestjs/passport

    $ npm install --save @nestjs/passport passport

     

    passport-jwt / @nestjs/jwt

    $ npm install --save @nestjs/jwt passport-jwt
    $ npm install --save-dev @types/passport-jwt

     

    passport-google-oauth20 / @types/passport-google-oauth20

    $ passport-google-oauth20 //google oauth2사용을 위해
    $ @types/passport-google-oauth20 //google oauth2사용을 위해

     

     

    [swagger]

    $ npm install --save @nestjs/swagger
    • NestJS V9 이상부터 swagger-ui-express가 더이상 필요 하지 않다.
    // main.ts
    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    import * as cookieParser from 'cookie-parser';
    import { ValidationPipe } from '@nestjs/common';
    import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
    
    const getSwaggerOptions = () => ({
    	swaggerOptions: {
    		persistAuthorization: true, //웹 페이지를 새로고침을 해도 Token 값 유지
    	},
    });
    
    async function bootstrap() {
    	const app = await NestFactory.create(AppModule);
    	const options = {
    		origin: true,
    		methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    		preflightContinue: false,
    		credentials: true,
    		allowedHeaders: 'Content-Type, Accept, Authorization',
    	};
    
    	// global pipes
    	app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
    
    	// cors
    	app.enableCors(options);
    
    	// cookie parser
    	app.use(cookieParser());
    
    	// swagger
    	const config = new DocumentBuilder()
    		.setTitle('fam API')
    		.setDescription('fam 서비스를 위한 API 문서')
    		.setVersion('1.0.0')
    		.addBearerAuth(
    			{
    				type: 'http',
    				scheme: 'bearer',
    				name: 'JWT',
    				in: 'header',
    			},
    			'accessToken',
    		)
    		.addSecurityRequirements('accessToken')
    		.build();
    
    	const document = SwaggerModule.createDocument(app, config);
    	SwaggerModule.setup('api/v1/swagger', app, document, getSwaggerOptions());
    
    	app.setGlobalPrefix('api');
    	await app.listen(5001);
    }
    bootstrap();

    [ Logger - middleware ]

     

    [ LoggingInterceptor, TimeoutInterceptor - controller에서 global - Interceptor ]

    @UseInterceptors(LoggingInterceptor, TimeoutInterceptor)
    @UseGuards(JwtGuard)
    @Controller('api/articles')
    export class ArticlesController {
    	...

    [ SuccessInterceptor - Interceptor ]

    • 응답 성공시 main.ts에 추가 해주는 global Interceptor 동일한 결과 response형식을 위함.

    [ HttpExceptionFilter - Filter ]

    • 응답 실패시 main.ts에 추가 해주는 global Filter 동일한 결과 response error 형식을 위함.

     

     

    [ Mail ]

    https://www.npmjs.com/package/@nestjs-modules/mailer

     

    @nestjs-modules/mailer

    NestJS - a mailer module (@mailer). Latest version: 1.9.1, last published: 22 days ago. Start using @nestjs-modules/mailer in your project by running `npm i @nestjs-modules/mailer`. There are 54 other projects in the npm registry using @nestjs-modules/mail

    www.npmjs.com

     

     

    [WebSocket]

    $ npm i --save @nestjs/websockets @nestjs/platform-socket.io socket.io

     

    [slug]

    $ npm i slugify

     

    [Events]

    $ npm i @nestjs/event-emitter
    728x90
Designed by Tistory.