블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2021. 10. 7. 10:59 React/Architecture

운영환경을 만들경우 번들링 파일간의 충돌을 최소화하기 위해 i18n 파일의 위치를 변경한다. 

  • Backend i18n은 public에 있을 필요가 없다. 
  • Frontend i18n은 위치도 간소화 한다. 

 

i18N 메세지 파일 위치 변경

Backend i18n 변경

apps/gateway/api/src/public/assets/i18n 의 assets 폴더를 apps/gateway/api/src 폴더 밑으로 위치 변경하고, assets/i18n/api 폴더를 assets/i18n 폴더 밑으로 이동한다. 

apps/gateway/api/project.json 에 assets 경로 추가하여 번들링시 포함되도록 한다. 

apps/gateway/api/src/environments/config.json 에서 i18n 위치를 변경한다.

Dashboard, Configuration, Back-Office의 API Backend에도 동일 환경을 적용한다. 특히 app.module.ts에 내역중 i18n고 TypeORM, Exception Filter 내역을 추가한다. 

import { join } from 'path';
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import { APP_FILTER, APP_GUARD } from '@nestjs/core';
import { ServeStaticModule } from '@nestjs/serve-static';
import { TypeOrmModule } from '@nestjs/typeorm';
import { getMetadataArgsStorage } from 'typeorm';

import { GatewayApiAppService, EntitiesModule, AuthModule, AuthMiddleware } from '@rnm/domain';
import { GlobalExceptionFilter, ormConfigService, RolesGuard, TranslaterModule } from '@rnm/shared';

import { environment } from '../environments/environment';
import { DashboardModule } from './dashboard/microservice/dashboard.module';
import { ConfigurationModule } from './configuration/microservice/configuration.module';
import { BackOfficeModule } from './back-office/microservice/back-office.module';
import { AppController } from './app.controller';
import { AuthController } from './auth/auth.controller';
import { UserController } from './user/user.controller';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, 'public'),
      exclude: [
        '/api/auth*',
        '/api/gateway*', '/api/dashboard*', '/api/configuration*', '/api/back-office*',
        '/dashboard*', '/configuration*', '/back-office*'
      ],
    }),
    // ORM
    TypeOrmModule.forRoot({
      ...ormConfigService.getTypeOrmConfig(),
      entities: getMetadataArgsStorage().tables.map(tbl => tbl.target)
    }),
    // i18n
    TranslaterModule,
    // TypeORM
    EntitiesModule,
    // MicroService
    DashboardModule,
    ConfigurationModule,
    BackOfficeModule,
    // Auth
    AuthModule
  ],
  controllers: [
    AuthController,
    AppController,
    UserController
  ],
  providers: [
    GatewayApiAppService,
    // Global Exception Filter
    {
      provide: APP_FILTER,
      useClass: GlobalExceptionFilter,
    },
    {
      provide: APP_GUARD,
      useClass: RolesGuard,
    },
  ]
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    if(!environment || !environment.production) {
      return;
    }

    consumer
      .apply(AuthMiddleware)
      .forRoutes(...[
        { path: '/dashboard*', method: RequestMethod.ALL },
        { path: '/configuration*', method: RequestMethod.ALL },
        { path: '/back-office*', method: RequestMethod.ALL },
        // { path: '/api/*', method: RequestMethod.ALL },
      ]);
  }
}

 

 

Frontend i18n 위치 변경

apps/gateway/web/src/assets/i18n/web/locale-en.json 파일의 위치를 apps/gateway/web/src/assets/i18n/locale-en.json 로 옮긴다. 

apps/gateway/web/src/environments/config.json 파일을 위의 그림처럼 추가하고, i18n, auth 관련 설정을 넣는다. I18N_JSON_PATH 앞에 /dashboard 가 추가된것에 주의 한다. 

// config.json
{
  "AUTH": {
    "SECRET": "iot_secret_auth",
    "EXPIRED_ON": "1d",
    "REFRESH_SECRET": "iot_secret_refresh",
    "REFRESH_EXPIRED_ON": "7d"
  },
  "I18N_LANG": "en",
  "I18N_JSON_PATH": "/dashboard/assets/i18n/"
}

apps/gateway/web/src/environments/environment.ts 파일에 config.json을 import하여 export 한다.

export const environment = {
  production: false,
};

export const config = require('./config.json');

apps/gateway/web/src/app/core/i18n.ts 파일을 libs/ui/src/lib/i18n 폴더 밑으로 옮기고, 내역을 수정한다. 

import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
import XHR from 'i18next-xhr-backend';

export function initI18N(config: any) {
  const backendOptions = {
    loadPath: (config.I18N_JSON_PATH || '/assets/i18n/') + 'locale-{{lng}}.json',
    crossDomain: true,
  };
  
  i18next
    .use(XHR)
    .use(initReactI18next)
    .init({
      backend: backendOptions,
      debug: true,
      lng: config.I18N_LANG || 'en',
      fallbackLng: false,
      react: {
        useSuspense: true
      }
    });
}

libs/ui/src/index.ts export를 추가한다. 

export * from './lib/ajax/http.service';
export * from './lib/i18n/i18n';

 

다음으로 apps/gateway/web/src/main.tsx 에서 initI18N을 초기화 한다. 

import * as ReactDOM from 'react-dom';

import { initI18N } from '@rnm/ui';

import App from './app/app';
import { config } from './environments/environment';

initI18N(config);
ReactDOM.render(<App />, document.getElementById('root'));

 

 

개발환경에서 Dashboard Web Dev Server로 연결하기

 

Gateway - Dashboard 로컬 개발시에는 총 4개의 프로세스가 구동되고 상호 연관성을 갖는다. 

  • Gateway API (NodeJS & NestJS), Gateway Frontend (Web Dev Server & React) 로 Gateway하나에 두개의 프로세스가 구동된다. 
  • Dashboard API, Dashboard Frontend 도 두개의 프로세스가 구동된다. 

4개 프로세스간의 관계

개발시에 전체 루틴을 처리하고 싶다면 위와 같은 Proxy 설정이 되어야 한다. 환경 설정을 다음 순서로 진행한다. 

 

Step-1) Gateway Web에서 Gateway API로 Proxy 

apps/gateway/web/proxy.conf.json 환경은 Dashboard, Configuration, Back-Office 모두를 proxy 한다. 그리고 apps/gateway/web/project.json 안에 proxy.conf.json과 포트 9000 을 설정한다. 

 

Step-2) Gateway API에서 Dashboard Web으로 Proxy

apps/gateway/api/src/environments/config.json 에서 REVERSE_ADDRESS가 기존 Dashboard API 의 8001 이 아니라, Dashboard Web의 9001 로 포트를 변경하면 된다. 

 

Step-3) Dashboard Web 에서 Dashboard API로 proxy

Dashboard API로 proxy 하기위해 apps/dashboard/web/proxy.conf.json 파일을 추가한다. api 호출은 dashboard api의 8001로 proxy 한다.

{
  "/dashboard/api/*": {
    "target": "http://localhost:8001",
    "secure": false,
    "changeOrigin": true,
    "ws": true
  }
}

apps/dashboard/web/project.json 에 설정한다. 

  • proxyConfig
  • port
  • baseHref: "/dashboard/"를 설정한다. "/dashboard"로 하면 안된다.

 

Step-4) Dashboard API 변경사항

apps/dashboard/api/src/public/dashboard 하위 내역을 모드 apps/dashboard/api/src/public으로 옮기고, dashboard  폴더를 삭제한다. 

apps/dashboard/api/src/environments/config.json 의 HTTP 포트는 8001 이다. 

 

테스트 

먼저 콘솔에서 gateway, dashboard web을 구동한다. 

$> nx serve gateway-web
NX  Web Development Server is listening at http://localhost:9000/

$> nx serve dashboard-web
>  NX  Web Development Server is listening at http://localhost:9001/

VSCode에서 gateway, dashboard api를 구동한다. 

브라우져에서 http://localhost:9000 을 호출하고, 로그인 해서 dashboard web 의 index.html 이 호출되는지 체크한다. 

proxy통해 dashboard web의 index.html 호출 성공

 

소스: https://github.com/ysyun/rnm-stack/releases/tag/ms-11

 

Release ms-11 · ysyun/rnm-stack

fixed i18n config and test env

github.com

 

posted by 윤영식
2021. 9. 23. 20:45 React/Architecture

micro service인 dashboard와 gateway간의 테스트 환경을 VS Code에 만들어 본다. 

 

VS Code 디버깅환경 설정

Step-1) package.json에 script 등록

각 애플리케이션의 build 스크립트를 등록한다. 

// package.json 
  "scripts": {
    "start": "nx serve",
    "build": "nx build",
    "test": "nx test",
    "build:gateway-api": "nx build gateway-api",
    "start:gateway-api": "nx serve gateway-api",
    "build:dashboard-api": "nx build dashboard-api",
    "start:dashboard-api": "nx serve dashboard-api",
    "build:configuration-api": "nx build configuration-api",
    "start:configuration-api": "nx serve configuration-api",
    "build:back-office-api": "nx build back-office-api",
    "start:back-office-api": "nx serve back-office-api"
  },

 

Step-2) .vscode 폴더안의 tasks.json 추가

tasks.json은 vscode의 디버깅 실행 환경설정파일인 launch.json에서 사용한다. 

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build:dashboard-api",
      "type": "shell",
      "command": "npm run build:dashboard-api"
    },
    {
      "label": "build:configuration-api",
      "type": "shell",
      "command": "npm run build:configuration-api"
    },
    {
      "label": "build:back-office-api",
      "type": "shell",
      "command": "npm run build:back-office-api"
    },
    {
      "label": "build:gateway-api",
      "type": "shell",
      "command": "npm run build:gateway-api"
    }
  ]
}

 

Step-3) .vscode 폴더안의 launch.json 추가

tasks.json의 설정내용은 "preLaunchTask"에 설정한다.

  • task.json의 build 를 먼저 실행한다. 빌드하면 루트폴더의 dist 폴더에 js, map이 생성된다. 
  • 이후 main.ts 소스에 breakpoint를 찍으면 디버깅을 할 수 있다. 
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Dashboard API",
      "program": "${workspaceFolder}/apps/dashboard/api/src/main.ts",
      "preLaunchTask": "build:dashboard-api",
      "outFiles": ["${workspaceFolder}/dist/apps/dashboard/api/**/*.js"]
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Gateway API",
      "program": "${workspaceFolder}/apps/gateway/api/src/main.ts",
      "preLaunchTask": "build:gateway-api",
      "outFiles": ["${workspaceFolder}/dist/apps/gateway/api/**/*.js"]
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Configuration API",
      "program": "${workspaceFolder}/apps/configuration/api/src/main.ts",
      "preLaunchTask": "build:configuration-api",
      "outFiles": ["${workspaceFolder}/dist/apps/configuration/api/**/*.js"]
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Back-Office API",
      "program": "${workspaceFolder}/apps/back-office/api/src/main.ts",
      "preLaunchTask": "build:back-office-api",
      "outFiles": ["${workspaceFolder}/dist/apps/back-office/api/**/*.js"]
    }
  ]
}

.vscode안의 launch.json과 tasks.json 파일

 

Gateway와 Micro Service간의 TCP 통신 테스트

Step-1) gateway의 dashboard.controller.ts에서 호출

  • dashboard.controller.ts에서 서비스호출
  • dashboard.service.ts 에서 breakpoint
// apps/gateway/api/src/app/dashboard/dashboard.controller.ts 
import { Controller, Get } from '@nestjs/common';

import { Observable } from 'rxjs';
import { DashboardService } from './dashboard.service';

@Controller('api/dashboard')
export class DashboardController {
  constructor(
    private readonly dashboardService: DashboardService
  ) { }

  @Get('sum')
  accumulate(): Observable<{ message: number, duration: number }> {
    return this.dashboardService.sum();
  }
}

// apps/gateway/api/src/app/dashboard/dashboard.service.ts 
import { Injectable, Inject } from "@nestjs/common";
import { ClientProxy } from "@nestjs/microservices/client";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";

@Injectable()
export class DashboardService {
  constructor(@Inject("DASHBOARD") private readonly client: ClientProxy) { }

  sum(): Observable<{ message: number, duration: number }> {
    const startTs = Date.now();
    const pattern = { cmd: 'dashboard-sum' };
    const payload = [1, 2, 3];
    return this.client
      .send<number>(pattern, payload)
      .pipe(
        map((message: number) => ({ message, duration: Date.now() - startTs }))
      );
  }
}

14줄 breakpoint

 

Step-2) Micro Service 인 dashboard에서 요청처리

  • 요청에 대한 sum 처리후 observable 로 반환
  • MessagePattern 데코레이터 적용
import { Controller, Get } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';

import { DashboardApiAppService } from '@rnm/domain';
import { from, Observable } from 'rxjs';

@Controller()
export class AppController {
  constructor(private readonly appService: DashboardApiAppService) { }

  @Get()
  getData() {
    return this.appService.getData();
  }

  @MessagePattern({ cmd: 'dashboard-sum' })
  accumulate(data: number[]): Observable<number> {
    console.log('calling sum from dashboard....');
    const sum = data[0] + data[1] + data[2];
    return from([sum]);
  }
}

20줄 breakpoint

 

Step-3) Dashboard, Gateway 서버 실행

디버깅으로 이동한다.

  • Dashboard API 실행
  • Gateway API 실행

실행결과

 

브라우져에서 호출

  • http://localhost:8000/api/dashboard/sum

디버깅 실행 영상

https://www.youtube.com/watch?v=UDWPnJdQUhI 

소스

https://github.com/ysyun/rnm-stack/releases/tag/ms-3

 

Release ms-3 · ysyun/rnm-stack

[ms-3] add debug config in vscode

github.com

 

posted by 윤영식
2021. 9. 20. 19:37 React/Architecture

React Nest를 기반으로 마이크로 서비스를 구축해 본다. 개발 환경은 Nx를 사용한다. Nx 환경구축은 [React HH-2] 글을 참조한다.

 

목차

  • Gateway, Dashboard등의 Application 생성
  • Application에서 사용하는 Library 생성
  • Gateway <-> MicroService Application간 통신 설정
    • api 호출: reverse proxy & tcp 설정
    • static assets 호출: static server 설정

 

Application 생성

4개의 카테고리에 각각 api, web 애플리케이션을 생성한다. 

  • gateway, dashboard, configuration, back-office
    • api, web

 

Step-1) 사전 준비환경 설치

글로벌 환경 설치를 한다. nvm 설치는 [React HH-2] 글을 참조한다.

$> npm i -g @angular/cli@latest 
$> npm i -g @nrwl/cli@latest 
$> npm i -g yarn@latest

node 버전은 nvm을 사용하여 14.18.0 를 사용한다. nvm 버전을 자동으로 설정하고 싶다면 

1) .zshrc파일에 다음 내용을 첨부한다. (Gist 코드 참조)

2) 작업 폴더에 .nvmrc 파일을 만든다.

// 코드: https://gist.github.com/ysyun/845ddd32467bb50af654e1e4605a4b50
// .zshrc
autoload -Uz add-zsh-hook
load-nvmrc() {
    local _CUR_NODE_VER="$(nvm version)"
    local _NVMRC_PATH="$(nvm_find_nvmrc)"

    if [[ -n "${_NVMRC_PATH}" ]]; then
        local _NVMRC_NODE_VER="$(nvm version "$(cat "${_NVMRC_PATH}")")"

        if [[ "${_NVMRC_NODE_VER}" == 'N/A' ]]; then
            local compcontext='yn:yes or no:(y n)'
            vared -cp "Install the unmet version ($(cat "${_NVMRC_PATH}")) in nvm (y/n) ?" _ANSWER
            if [[ "${_ANSWER}" =~ '^y(es)?$' ]] ; then
                nvm install
            fi
        elif [[ "${_NVMRC_NODE_VER}" != "${_CUR_NODE_VER}" ]]; then
            nvm use
        fi
    elif [[ "${_CUR_NODE_VER}" != "$(nvm version default)" ]]; then
        echo -e "Reverting to the default version in nvm"
        nvm use default
    fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc

// 작업 폴더에 .nvmrc 파일을 생성하고, 버전을 기입힌다. 아래 내용 참조
// .nvmrc
14.18.0

 

Step-2) NX 개발환경 생성

create-nx-workspace@latest를 이용하고, .nvmrc 파일을 생성한다. .zshrc가 적용되고, rnm-stack 폴더에 진입하면 자동으로 14.18.0 버전이 적용된다. rnm은 React Nest Micro-service의 약어이다.

$> npx create-nx-workspace@latest
✔ Workspace name (e.g., org name)     · rnm-stack
✔ What to create in the new workspace · react
✔ Application name                    · gateway/web
✔ Default stylesheet format           · scss
✔ Use Nx Cloud? (It's free and doesn't require registration.) · No


$> cd rnm-stack
$> echo "14.18.0" > .nvmrc

다음은 api 애플리케이션을 Nest기반으로 생성한다.

// nest 제너레이터 설치
$> yarn add -D @nrwl/nest@latest

// api 생성
$> nx g @nrwl/nest:app gateway/api

다음으로 루트폴더에 있는 workspace.json 파일을 각 api와 web폴더에 project.json 파일을 생성하여 설정을 옮긴다. 이후 생성되는 애플리케이션들은 자동으로 project.json 파일로 생성된다. 

// workspace.json
{
  "version": 2,
  "projects": {
    "gateway-api": "apps/gateway/api",  <== project.json 파일의 위치 지정
    "gateway-web": "apps/gateway/web",
    "gateway/web-e2e": "apps/gateway/web-e2e"
  },
  ... 생략 ...
  "defaultProject": "gateway-web"
}

project.json 파일들

 

테스트 "nx serve gateway-web" 을 수행하면 정상적으로 dev server가 수행된다.

$> nx serve gateway-web

> nx run gateway-web:serve
>  NX  Web Development Server is listening at http://localhost:4200/

나머지 dashboard, configuration, back-office도 생성한다.

// react application
$> nx g @nrwl/react:app dashboard/web
$> nx g @nrwl/react:app configuration/web
$> nx g @nrwl/react:app back-office/web

// nest application
$> nx g @nrwl/nest:app dashboard/api
$> nx g @nrwl/nest:app configuration/api
$> nx g @nrwl/nest:app back-office/api

전체 생성 애플리케이션과 workspace.json 내역

 

Libraries 생성

다음으로 libs 폴더 하위로 라이브러리들을 생성한다. @rnm/page, @rnm/ui, @rnm/domain, @rnm/shared 로 import하여 사용한다.  

  • page
  • ui
  • domain
  • shared
$> nx g @nrwl/react:lib page --importPath=@rnm/page --publishable
$> nx g @nrwl/react:lib ui --importPath=@rnm/ui --publishable
$> nx g @nrwl/nest:lib domain --importPath=@rnm/domain --publishable
$> nx g @nrwl/nest:lib shared --importPath=@rnm/shared --publishable

libs 폴더밑으로 4개 라이브러리 생성

 

 

Micro Service Communication Channel 설정

다음은 애플리케이션간의 연결을 위한 통신부분을 설정한다. NestJS 기반으로 microservice 생성을 위해 패키지를 설치한다. NestJS버전을 7.6.18 버전으로 업데이트 한다. (현재 8.*은 microservice 버그가 있다. 작동불능)

$> yarn add @nestjs/microservices


// package.json 에서 nestjs의 모든 패키지의 버전을 업데이트 한다. 
  "dependencies": {
    "@nestjs/common": "^7.6.18", <== 요기
    "@nestjs/core": "^7.6.18", <== 요기
    "@nestjs/microservices": "^7.6.18", <== 요기
    "@nestjs/platform-express": "^7.6.18", <== 요기
    "@nestjs/serve-static": "^2.2.2",
    "core-js": "^3.6.5",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-router-dom": "5.2.0",
    "reflect-metadata": "^0.1.13",
    "regenerator-runtime": "0.13.7",
    "rxjs": "~6.6.3",
    "tslib": "^2.0.0"
  },
  "devDependencies": {
    "@nestjs/schematics": "^7.3.1", <== 요기, 7최신이 7.3.1
    "@nestjs/testing": "^7.6.18", <== 요기
    ...
  }
  
  
  // nestjs 모든 패키지의 업데이트 버전을 재설치한다.
  $> yarn

 

Step-1) Micro Service 설정

  • dashboard, configuration, back-office 3가지 micro service
    • http server & static server
      • dashboard: 8001, configuration: 8002, back-office: 8002 HTTP port를 사용한다.
    • api server
      • dashboard: 8100, configuration: 8200, back-office: 8300 TCP port를 사용한다.

apps/dashboard/api/src 하위로 public 폴더를 하위로 dashboard 폴더를 추가로 생성한 후 index.html 파일을 생성한다.

  • apps/dashboard/api/src/environments폴더에 config.json 파일을 생성한다.
  • apps/dashboard/api/project.json 에  "assets" 파트에 설정을 추가한다. 
    "assets": ["apps/dashboard/api/src/environments", "apps/dashboard/api/src/public"]

libs/shared/src/lib 밑에 configuration 폴더를 생성하고, config.service.ts 와 config.model.ts을 생성한다. config.json 파일을 읽기위한 용도이다. index.ts에  export도 설정한다.

// config.service.ts
import * as fs from "fs";
import { join } from 'path';
import { GatewayConfiguration, MicroServiceConfiguration } from "./config.model";

export const loadMicroServiceConfiguration = (message = '[LOAD] config.json file'): MicroServiceConfiguration => {
  console.log(`${message}:`, `${__dirname}/environments/config.json`);
  const jsonFile = fs.readFileSync(join(__dirname, 'environments', 'config.json'), 'utf8');
  return JSON.parse(jsonFile);
}

export const loadGatewayConfiguration = (message = '[LOAD] config.json file'): GatewayConfiguration => {
  console.log(`${message}:`, `${__dirname}/environments/config.json`);
  const jsonFile = fs.readFileSync(join(__dirname, 'environments', 'config.json'), 'utf8');
  return JSON.parse(jsonFile);
}


// config.model.ts 
export interface MicroServiceConfiguration {
  REVERSE_CONTEXT?: string;
  REVERSE_ADDRESS?: string;
  HTTP_PORT?: number,
  TCP_HOST?: string;
  TCP_PORT?: number,
  GLOBAL_API_PREFIX?: string;
}

export interface GatewayConfiguration {
  HTTP_PORT?: number,
  GLOBAL_API_PREFIX?: string;
  DASHBOARD?: MicroServiceConfiguration;
  CONFIGURATION?: MicroServiceConfiguration;
  BACK_OFFICE?: MicroServiceConfiguration;
}


// index.ts
export * from './lib/configuration/config.model';
export * from './lib/configuration/config.service';

apps/dashboard/api/src/main.ts 파일을 수정한다. http server를 위한 listen port를 설정하고, microservice client가 연결토록 TCP로 연결 준비를 한다. loadMicroServiceCofiguration 함수를 "@rnm/shared" 패키지로 부터 위치 투명하게 (마치 node_modules에 설치된 것처럼) import 할 수 있다.

import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { Transport, MicroserviceOptions } from '@nestjs/microservices';

import { loadMicroServiceConfiguration } from '@rnm/shared';

import { AppModule } from './app/app.module';

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

  // Load config.json file
  const config = loadMicroServiceConfiguration();

  // // Setup tcp server for api
  const options: MicroserviceOptions = {
    transport: Transport.TCP,
    options: { host: config.TCP_HOST, port: config.TCP_PORT || 8100 }
  };
  app.connectMicroservice(options);
  app.startAllMicroservices();

  // // Setup http server for web
  const httpPort = config.HTTP_PORT || process.env.HTTP_PORT || 8001;
  const globalPrefix = config.GLOBAL_API_PREFIX || '/api';
  app.setGlobalPrefix(globalPrefix);
  await app.listen(httpPort, () => {
    Logger.log(`Listening at http://localhost:${httpPort}${globalPrefix}`);
  });
}

bootstrap();

확인 & 테스트 

// LISTEN 포트 확인
$> netstat -an |grep 8100
tcp4       0      0  *.8100                 *.*                    LISTEN
$> netstat -an |grep 8001
tcp46      0      0  *.8001                 *.*                    LISTEN

// gateway 실행
$> nx serve dashboard-api

// other console
$> curl -X GET "http://localhost:8001/api" 
{"message":"Welcome to dashboard/api in libs"}

configuration, back-office도 동일하게 적용한다.

 

 

Step-2) Micro Service의 HTTP port가 static file 서비스토록 설정

@nestjs/serve-static (v2.2.2) 패키지를 설치한다. (참조)

$> yarn add @nestjs/serve-static

 

apps/dashboard/api/src/app/app.module.ts 에 static 환경을 설정한다. rootPath는 public 폴더를 만든다. exclude는 global prefix인 api를 제외한다. public 폴더에 index.html 을 만들어 본다. 향후 react기반 SPA 번들파일을 위치할 것이다. 

import { Module } from '@nestjs/common';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

import { DashboardApiAppService } from '@rnm/domain';

import { AppController } from './app.controller';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, 'public'),
      exclude: ['/api*', '/dashboard/api*'],
    }),
  ],
  controllers: [AppController],
  providers: [DashboardApiAppService],
})
export class AppModule { }

// index.html
dashboard home

재실행 후, dashboard context path로 브라우져에서 확인한다. public/dashboard/assets/images 밑으로 샘플 이미지 복사

// public/dashboard/index.html 내역

<html>
  <head>
    <base href="dashboard" />
  </head>
  <body>
    welcome to dashboard! <img src="/dashboard/assets/images/dashboard.png" />
  </body>
</html>

 

Step-3) Micro Service의 응답을 위한 TCP MessagePattern 데코레이터 생성

apps/dashboard/api/src/app/app.controller.ts 에서 TCP 요청에 대한 응답 코드를 작성한다. TCP는 MessagePattern 데코레이터를 통해 응답하고 반환은 Primitive type, Promise, Observable 다 가능하다. 만일 Observable로 하면 gateway 측에서 Observable로 대응할 수 있다. 

  • { cmd: 'dashboard-sum' } 은 gateway로부터 오는 Key이다.
import { Controller, Get } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';

import { DashboardApiAppService } from '@rnm/domain';
import { from, Observable } from 'rxjs';

@Controller()
export class AppController {
  constructor(private readonly appService: DashboardApiAppService) { }

  @Get()
  getData() {
    return this.appService.getData();
  }

  @MessagePattern({ cmd: 'dashboard-sum' })
  accumulate(data: number[]): Observable<number> {
    console.log('calling sum from dashboard....');
    const sum = data[0] + data[1] + data[2];
    return from([sum]);
  }
}

테스트는 Gateway까지 설정후 진행한다.

 

Step-4) Gateway 설정

  • gateway
    • http server & static server
    • reverse proxy
    • api client

config.json 파일을 apps/gateway/api/src/environment  폴더밑으로 생성하고 하기와 같이 설정한다.

{
  "HTTP_PORT": 8000,
  "DASHBOARD": {
    "REVERSE_CONTEXT": "dashboard",
    "REVERSE_ADDRESS": "http://127.0.0.1:8001",
    "HTTP_PORT": 8001,
    "TCP_HOST": "0.0.0.0",
    "TCP_PORT": 8100,
    "GLOBAL_API_PREFIX": "/api"
  },
  "CONFIGURATION": {
    "REVERSE_CONTEXT": "configuration",
    "REVERSE_ADDRESS": "http://127.0.0.1:8002",
    "HTTP_PORT": 8002,
    "TCP_HOST": "0.0.0.0",
    "TCP_PORT": 8200,
    "GLOBAL_API_PREFIX": "/api"
  },
  "BACK_OFFICE": {
    "REVERSE_CONTEXT": "back-office",
    "REVERSE_ADDRESS": "http://127.0.0.1:8003",
    "HTTP_PORT": 8003,
    "TCP_HOST": "0.0.0.0",
    "TCP_PORT": 8300,
    "GLOBAL_API_PREFIX": "/api"
  }
}

apps/gateway/api/src/main.ts는 http server를 설정한다.

  • global prefix를 설정하지 않고, 각 controller에서 설정한다.
  • gateway api 호출은 "api/gateway"
  • dashboard api 호출은 "api/dashboard". 다른 microservice도 동일하다.
// gateway의 main.ts
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

import { loadGatewayConfiguration } from '@rnm/shared';

import { AppModule } from './app/app.module';

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

  // Load config.json file
  const config = loadGatewayConfiguration();

  const httpPort = config.HTTP_PORT || process.env.HTTP_PORT || 8000;
  await app.listen(httpPort, () => {
    Logger.log(`Listening at http://localhost:${httpPort}`);
  });
}

bootstrap();


// app.controller.ts
@Controller('api/gateway') <== 요기
export class AppController { ... }


// dashboard.controller.ts
@Controller('api/dashboard') <== 요기
export class DashboardController { ... }

apps/gateway/api/src/app/app.module.ts에서는 static file 서비스 폴더를 지정한다. reverse proxy를 위해 아래 3개의 exclude를 추가한다. web context처럼 사용될 것이다.

  • dashboard
  • configuration
  • back-office
import { Module } from '@nestjs/common';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

import { GatewayApiAppService } from '@rnm/domain';

import { AppController } from './app.controller';
import { DashboardModule } from './dashboard/dashboard.module';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, 'public'),
      exclude: [
        '/api/gateway*', '/api/dashboard*',
        '/dashboard*', '/configuration*', '/back-office*'
      ],
    }),
    DashboardModule
  ],
  controllers: [AppController],
  providers: [GatewayApiAppService]
})
export class AppModule { }

gateway, back-office, configuration, dashboard등에서 사용하는 api service 를 domain library로 옮기고, 명칭을 수정하여 import해서 사용한다. 예로 GatewayApiAppService, DashboardApiAppService와 같다. api service중에 라이브러리성으로 옮겨도 될 만한 것들을 domain 라이브러리 밑으로 작성한다. 예로 여러 곳에서 호출되는 공통 api의 경우 또는 업무적인 묶음단위로 api를 관리하고 싶을 경우이다. 해당 api를 라이브러리로 빼는 이유는 향후 다른 UI에서 사용하거나 또는 UI가 바뀌어도 업무적인 api에 변경이 없을 경우를 가정한 것이다.

 

Step-5) Gateway에 Micro Service쪽으로 reverse proxy 설정하기

micro service 인 dashboard, configuration, back-office는 자신의 http web server로써 static file을 서비스하고, tcp를 통해 api를 전송한다. 개발시에는 gateway를 구동하지 않고, micro service만 실행한다면 http를 통해 api 서비스 추가하면 될 것이다.

Gateway에서 reverse proxy되는 3개 context

 

http-proxy-middleware를 설치한다. 

$>  yarn add http-proxy-middleware

 

다음으로 apps/gateway/api/src/app 폴더 밑으로 dashboard 폴더를 생성하고,  dashboard용 controller, service, module과 dashboard.proxy.ts 파일들을 생성한다.

  • NestMiddleware를 상속받아 use를 구현한다.
// dashboard.proxy.ts ==> dashboard-proxy.middleware.ts 로 추후 명칭 변경됨
/* eslint-disable @typescript-eslint/no-explicit-any */
import { NestMiddleware, Logger } from '@nestjs/common';
import { loadGatewayConfiguration } from '@rnm/shared';
import { createProxyMiddleware } from 'http-proxy-middleware';

export class DashboardReverseProxyMiddleware implements NestMiddleware {
  private config = loadGatewayConfiguration();
  private proxyOptions = {
    target: this.config.DASHBOARD.REVERSE_ADDRESS,
    secure: false,
    onProxyReq: (proxyReq: any, req: any, res: any) => {
      Logger.debug(`[DashboardReverseProxyMiddleware]: Proxying ${req.method} request originally made to '${req.url}'`);
    },
  };
  private proxy: any = createProxyMiddleware(this.proxyOptions);

  use(req: any, res: any, next: () => void) {
    this.proxy(req, res, next);
  }
}

dashboard.module.ts에 다음과 같이 dashboard에 TCP로 접근하는 Client설정을 한다. 그리고 ProxyMiddleware를 설정한다.

import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';

import { loadGatewayConfiguration } from '@rnm/shared';

import { DashboardController } from './dashboard.controller';
import { DashboardReverseProxyMiddleware } from './dashboard.proxy';
import { DashboardService } from './dashboard.service';

const config = loadGatewayConfiguration();

@Module({
  imports: [
    // dashboard쪽 api 호출을 위한 TCP Client Proxy 등록
    ClientsModule.register([
      {
        name: "DASHBOARD",
        transport: Transport.TCP,
        options: {
          host: config.DASHBOARD.TCP_HOST,
          port: config.DASHBOARD.TCP_PORT
        }
      }
    ])
  ],
  controllers: [DashboardController],
  providers: [DashboardService],
})
export class DashboardModule implements NestModule {
  // middleware 적용
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(DashboardReverseProxyMiddleware)
      .forRoutes({ path: config.DASHBOARD.REVERSE_CONTEXT, method: RequestMethod.ALL });
  }
}

전체 코드 준비는 되었고, 다음 글에서는 MS Code에서 Debugging을 통해 위의 코드를 테스트해 본다.

 

소스: https://github.com/ysyun/rnm-stack/releases/tag/ms-2

 

 

<참조>

- 마이크로 서비스 설정 예제
https://github.com/danmt/microservices-basics

 

GitHub - danmt/microservices-basics: This project intention is to show microservices basic concepts in NestJs

This project intention is to show microservices basic concepts in NestJs - GitHub - danmt/microservices-basics: This project intention is to show microservices basic concepts in NestJs

github.com

- reverse proxy 설정 예제

https://github.com/baumgarb/reverse-proxy-demo

 

GitHub - baumgarb/reverse-proxy-demo: Reverse proxy demo with NestJS and http-proxy-middleware

Reverse proxy demo with NestJS and http-proxy-middleware - GitHub - baumgarb/reverse-proxy-demo: Reverse proxy demo with NestJS and http-proxy-middleware

github.com

- http-proxy-middleware 패키지

https://github.com/chimurai/http-proxy-middleware

 

GitHub - chimurai/http-proxy-middleware: The one-liner node.js http-proxy middleware for connect, express and browser-sync

:zap: The one-liner node.js http-proxy middleware for connect, express and browser-sync - GitHub - chimurai/http-proxy-middleware: The one-liner node.js http-proxy middleware for connect, express a...

github.com

 

posted by 윤영식
prev 1 next