Skip to main content

Command Palette

Search for a command to run...

OpenAPI Generator를 활용한 API 인터페이스 자동 생성

Published
2 min readView as Markdown
K

프론트엔드 개발자 김가영입니다. 개발과 일에 대한 생각을 주로 씁니다. https://velog.io/@kykim_dev/posts (2023 이전 블로깅)

TypeScript로 프론트엔드 개발 작업시 API 응답 값에 대한 타입 지정이 필요하다. 이때 많은 양의 타입을 자동화해주는 모듈을 사용할 수 있다. OpenAPI Generator는 Swagger에서 제공하는 자동화 도구 중 하나로 클라이언트에서 사용가능한 타입을 자동으로 생성해 준다. Swagger와 연동, TypeScript 타입을 생성하는 대표적인 npm 패키지로 openapi-typescript-codegen 가 있다.

openapi-typescript-codegen

  • OAS(OpenApi Specification)를 기반으로 TypeScript 타입을 생성하는 npm 패키지

  • JSON, YAML 파일 및 Swagger에서 설정된 model type 값에서 타입 추론

  • 서버 API의 명확한 model type 정의 필요

설치 및 실행

npm i node-fetch openapi-typescript-codegen -D
  • package.json script 추가
{
    "generate:openApi-typescript": "node ./scripts/generate-openapi-types.js",
}

스크립트 생성

const path = require("path");
const fs = require("fs");
const { promisify } = require("util");
const fetch = require("node-fetch");
const OpenAPI = require("openapi-typescript-codegen");

(async function () {
  // yaml or json
  const format = "json";
  // Swagger groups Array
  const groups = [
    "Global-Cocone",
    "Hello-Cocone",
    "Hello-Cocone-Admin",
    "Hello-Cocone-Login",
  ];
  // swagger-url or yaml
  const specURL = ""; // ex) swaggerURL/api-docs?group';

  const accessAsync = promisify(fs.access);
  const mkdirAsync = promisify(fs.mkdir);
  const writeFileAsync = promisify(fs.writeFile);

  const makeDirectory = async (path) => {
    try {
      await accessAsync(path);
    } catch (err) {
      if (err.code === "ENOENT") {
        await mkdirAsync(path, { recursive: true });
      } else {
        throw err;
      }
    }
  };

  try {
    for (let group of groups) {
      const outputPath = path.resolve(
        // 타입이 생성될 경로
        path.join(__dirname, "..", `src/types/${group.toLowerCase()}`),
      );

      const docFilePath = path.join(outputPath, `spec.${format}`);

      const response = await fetch(`${specURL}=${group}`);
      const data = await response.text();

      await makeDirectory(outputPath);
      await writeFileAsync(docFilePath, data);

      await OpenAPI.generate({
        input: docFilePath,
        output: outputPath,
        useOptions: true,
        useUnionTypes: true,
        exportServices: false,
        exportCore: false,
      });
    }
  } catch (error) {
    console.error(error);
  }
})();

실행

npm run generate:openApi-typescript

결과

  • src/types 폴더 내부에 groups 로 분리한 폴더 생성

  • models 폴더 내부에 interface{}로 타입 정의된 .ts 파일 생성

More from this blog

React 렌더링 최적화

React 렌더링이란? 리액트에서 렌더링이란, 컴포넌트가 현재 props와 state의 상태에 기초하여 UI를 어떻게 구성할지 컴포넌트에게 요청하는 작업을 의미한다. 즉 사용자 화면에 View(내용)를 보여 주는 것. 초기 렌더링 렌더링을 담당하는 render 함수는 컴포넌트의 정보를 이용해 화면을 구성(렌더링)한다. 컴포넌트 내부에는 또 다른 컴포넌트들이 들어갈 수 있어, render 함수가 실행되면 그 내부에 있는 컴포넌트들도 재귀적으로 렌...

May 21, 20243 min read

로컬에서 Aws Ec2 인스턴스에 배포하기

EC2 (컴퓨팅) Elastic Compute Cloud(EC2)로 클라우드 컴퓨팅 서비스 클라우드를 통해 서버, 스토리지, 데이터베이스 등의 컴퓨팅 서비스를 제공하는 것으로 AWS에서 원격으로 제어할 수 있는 가상의 컴퓨터 한 대를 임대하는 것과 같다. 제공되는 가상 이미지를 ‘인스턴스(Instance)’라고 하며, 필요에 따라 사양(CPU 코어 수, 메모리 용량, 스토리지)을 변경할 수 있다. 서버에 Build 가져오기 1. 로컬에...

Apr 10, 20242 min read

DevNotes by kykim

23 posts