View

TIL | Node_개발환경세팅

Melody:) 2021. 10. 5. 13:03

이번 블로그에서는 Node.js 개발환경 세팅 방법을 알아보도록 하겠습니다^ㅡ^


NVM(Node Version Manager) 설치

https://gist.github.com/falsy/8aa42ae311a9adb50e2ca7d8702c9af1

1. 터미널에 아래 명령문 입력하여 링크로 설치

$ sudo curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.1/install.sh | bash

2. 설치 확인

$ nvm ls
-bash: nvm: command not found

3. 에러가 난다면 vim 으로 아래 파일 생성 또는 수정하여

$ vim ~/.bash_profile

아래 코드 추가

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm

4. 파일 재시작

source ~/.bash_profile

5. 설치 재확인

$ nvm ls
->       system
node -> stable (-> N/A) (default)
iojs -> N/A (default)

Node 설치

1. 아래 명령문 입력하여 안전화된 6.10.1

$ nvm install 6.10.1

2. 버전 확인

node -v

3. 기타 사용방법

node -v                      // 내가 사용하고 있는 Node 버전 확인하기
nvm list available      // 사용 가능한 버전 조회하기
nvm install 14.15.4  // 14.15.4(LTS) 버전 다운로드하기
nvm list                     // 설치 되어있는 버전확인하기
nvm use 14.15.4             // 14.15.4 버전 사용하기
node -v

nest 환경 구축 가이드 최초 구축 시

1.NestJS CLI 설치(7.6이상)

$ npm install -g @nestjs/cli

참고 : [https://velog.io/@seongkyun/%EC%B0%8D%EC%96%B4%EB%A8%B9%EB%8A%94-NestJS-%EC%B4%88%EA%B8%B0%EC%84%A4%EC%A0%95]

2. 앱 생성

nest new <앱이름>

3. 앱으로 이동

cd <앱이름>

4. yarn

yarn

5. 기존 프로젝트의 config 복사

6. app.module.ts에 config를 import

기존 프로젝트 클론 시

1. git 클론

git clone <리포지토리이름>

2. 앱으로 이동

cd <리포지토리이름>

3. yarn

yarn

node - swagger 사용법

1. 모듈 실행

npm i swagger-jsdoc swagger-ui-express --save-dev

또는 fastify를 사용한다면 아래 명령문 사용

$ npm install --save @nestjs/swagger fastify-swagger

1-1. Dto

[https://www.notion.so/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F30b1f5d4-a97c-436d-9204-0e8a2b1813c9%2FUntitled.png?table=block&id=195931d1-fd98-4412-80ce-d3f77c942e99&spaceId=e0f334c2-f568-4e1e-a400-7bda0ac53be1&width=580&userId=2b5cac6a-b072-43d9-9711-6eb9444573c8&cache=v2]

  • ApiProperty, ApiPropertyOptional : swagger 적용
  • → ApiPropertyOptional 사용시 IsOptional 꼭 같이 사용!
  • isNumber, isString... : 받아오는 값 체크
  • (optional)Type : 간혹 적용하지 않았을때 제대로 작동하지 않는 경우가 있어 인지하고 있으면 좋습니다 : )

[https://www.notion.so/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2Ffea4e637-121c-456e-9c62-401d31ea6687%2FUntitled.png?table=block&id=3f66e446-3791-4b8b-b59c-faec479cb8bd&spaceId=e0f334c2-f568-4e1e-a400-7bda0ac53be1&width=1080&userId=2b5cac6a-b072-43d9-9711-6eb9444573c8&cache=v2]

  • dto를 잘 작성해 주셨다면 어떤 데이터가 필요한지 다른분들께서 편하게 확인 가능합니다

1-2. Controller

  • api 별 summary, description 등 추가 할수 있습니다!

[https://www.notion.so/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F75a89a5d-ed90-4a0a-ab8f-16865f437de9%2FUntitled.png?table=block&id=0ac84318-f465-4019-8ccb-375ed863565c&spaceId=e0f334c2-f568-4e1e-a400-7bda0ac53be1&width=1540&userId=2b5cac6a-b072-43d9-9711-6eb9444573c8&cache=v2]

[https://www.notion.so/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F55af27f0-a596-4fa2-9378-c31df79bfb8c%2FUntitled.png?table=block&id=c773489d-60c8-4ee3-b4cf-652f86dbc423&spaceId=e0f334c2-f568-4e1e-a400-7bda0ac53be1&width=1540&userId=2b5cac6a-b072-43d9-9711-6eb9444573c8&cache=v2]

활용도 있는 description 작성

[https://www.notion.so/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F08a83136-3fd7-4033-a18d-3bd1707213a4%2FUntitled.png?table=block&id=2b41d3fb-91e8-4a9a-8f91-646858c29f56&spaceId=e0f334c2-f568-4e1e-a400-7bda0ac53be1&width=770&userId=2b5cac6a-b072-43d9-9711-6eb9444573c8&cache=v2]

결과: [https://www.notion.so/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2Ff91072ed-0426-403a-be9e-3c56a18857b9%2FUntitled.png?table=block&id=789693c3-09fc-4def-bbb1-798325034e67&spaceId=e0f334c2-f568-4e1e-a400-7bda0ac53be1&width=670&userId=2b5cac6a-b072-43d9-9711-6eb9444573c8&cache=v2]

2-1. Bootstrap에서 사용 하는 법

import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const config = new DocumentBuilder()
    .setTitle('Cats example')
    .setDescription('The cats API description')
    .setVersion('1.0')
    .addTag('cats')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);
}
bootstrap();

2-2. swagger.js : 기본설정

const swaggerJSDoc  = require('swagger-jsdoc');
const swaggerUi     = require('swagger-ui-express');

// Swagger definition
// You can set every attribute except paths and swagger
// https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md
const swaggerDefinition = {
    info: {                                                // API informations (required)
        title: 'Glocalize Translation Tool API',           // required
        version: '1.0.0',                                  // required
        description: 'Translation Tool API Specification', // Description (optional)
    }
};

// Options for the swagger docs
const options = {
    swaggerDefinition: swaggerDefinition,  // Import swaggerDefinitions
    apis: [                                // Path to the API docs
        'routes/*.js',                     // v1,v2... 확장가능(swaggerDefinition,swaggerSpec도 버전별로 따로 생성해야 함)
        'routes/*/*.js'
    ]
};

// Initialize swagger-jsdoc -> returns validated swagger spec in json format
const swaggerSpec = swaggerJSDoc(options);

module.exports = {
    swaggerUi,
    swaggerSpec
}

2-3. app.js : 라우팅 설정

const { swaggerSpec, swaggerUi } = require('./routes/swagger');

// api개수가 많아졌을 경우 검색옵션을 추가해주면 좋다 setup(swaggerSpec, { explorer: true })
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec))

http://localhost:8080/api-docs → 접속

2-4. API 등록

/**
 * @swagger  //required
 *
 * /main/getSubtitles:
 *   get:
 *     tags: [Todo] //tag별 리스트화 가능( 꼭 []안에 넣어줘야 함 )
 *     description: 자막 정보 가져오기
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: taskId
 *         description: taskId
 *         in: query
 *         required: true
 *         type: integer
 *       - name: subtaskType
 *         description: WORK / QC / CONFIRM / FINALIZE
 *         in: query
 *         required: true
 *         type: string
 *     responses:
 *       ok:
 *         description: '200'
 *         schema:
 *           type: object
 *           properties:
 *             message:
 *               type: string
 *               default: ok //Example Value 기본값 설정
 *             data:
 *               type: array
 *               items:
 *                 $ref: '#/definitions/Subtitles' //문자열로 감싸기
 *             status:
 *               type: integer
 *       no data:
 *         description: '200'
 *         schema: //이 위치는 items 사용하면 ref연결 안됨
 *           $ref: '#/definitions/noData'
 */

3. 주의사항

  1. 들여쓰기시 tap사용하면 err → 무조건 스페이스 사용!
  2. array 사용시 → items 설정 해줘야 err 안난다
  3. properties: data: type: array items: type: string

4. 실행시키기

$ npm run start

또는

$ nest start

기타참고 : yarn, npm : 자바스크립트 자바스크립트 패키지 매니저 설치

https://hello-bryan.tistory.com/94

https://hello-bryan.tistory.com/94

[https://butter-ring.tistory.com/17]

'NestJS' 카테고리의 다른 글

TIL | TypeScript_기본문법2  (0) 2021.10.10
TIL | TypeScript_기본 문법1  (0) 2021.10.10
TIL | Typescript_Setting_초기개발환경세팅  (0) 2021.10.07
TIL | Node.js_filter()  (0) 2021.10.04
TIL | Node.js_Map()  (0) 2021.10.04
Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31