[Nest.js] 맨땅에 헤딩 - Blog API 제작기 1편

2021. 6. 5. 20:54Nest.js

평소에 Nest.js관련 글에 API 만들기 관련된 포스트가 없어 직접 만들면서 공부하게 되었습니다. 해당 블로그는 공부를 남기기 위한 용도입니다. 피드백 부탁드립니다.

1. 새로운 프로젝트를 생성하자.

블로그 포스팅에 앞서서 가장 먼저 내가 원하는 디렉토리에 프로젝트를 먼저 생성해봅시다.

Nest.js는 다음 명령어로 프로젝트를 쉽게 생성 할 수 있습니다.

nest new project-name

프로젝트를 생성 후 프로젝트를 살펴보면 다음과 같은 구성으로 되어있습니다.

.
├── .eslintrc.js
├── .gitignore
├── .prettierrc
├── README.md
├── nest-cli.json
├── package-lock.json
├── package.json
├── src
│   ├── app.controller.spec.ts
│   ├── app.controller.ts
│   ├── app.module.ts
│   ├── app.service.ts
│   └── main.ts
├── test
│   ├── app.e2e-spec.ts
│   └── jest-e2e.json
├── tsconfig.build.json
└── tsconfig.json

우리가 작성 할 코드는 src에서 작성 하게 될것입니다. test폴더는 E2E테스트를 하기 위한 폴더입니다.
그 외에는 프로젝트를 구성하는 기본 세팅 내용을 담고 있습니다.

2. 프로젝트의 기본 세팅을 바꾸어 보자.

저는 VSCode의 환경세팅으로 prettier를 사용하고 있습니다. 따라서 Nest.js가 자동으로 생성해주는 .prettierrc를 삭제를 하겠습니다.
또한, ESLint파일이 어디서나 잘 작동되도록 .eslintrc.js를 조금 수정하도록 하겠습니다.

const path = require("path");

module.exports = {
    parser: "@typescript-eslint/parser",
    parserOptions: {
        project: path.join(__dirname, "tsconfig.json"),
        tsconfigRootDir: __dirname,
        sourceType: "module"
    },
    plugins: ["@typescript-eslint/eslint-plugin"],
    extends: ["plugin:@typescript-eslint/recommended", "prettier/@typescript-eslint", "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"
    }
};

사실 바꾼건 별로 없습니다. path를 통해서 경로를 좀 유동적 (dynamic)하게 바꾸고 ignorePatterns를 추가 한것 뿐입니다.

또, 한가지 추가적으로 처음에 만들때 생긴 tsconfig.json에서 targetES2020으로 바꾸고 저장하겠습니다.

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2020",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true
  }
}

3. 프로젝트를 실행해보자.

프로젝트 실행에 앞서 우리는 /src/main.ts를 보겠습니다.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

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

위 코드에서는 큰 내용은 없고 우리가 3000번 포트를 통해 앱(Nest.js)를 실행한다고 하는 것을 볼수 있습니다.

그럼 이제, 다음 명령어를 프로젝트의 터미널에서 실행해봅시다.

npm run start:dev

당연하지만 우리의 코드에 에러가 없다는 메시지와 서버가 시작되었습니다.

해당 웹페이지로 접속을 해보겠습니다.

다음 포스트에서는 프로젝트의 main.ts를 세팅하는 내용을 작성하겠습니다.