Node.js 환경에서Pythhon의FastapI 같은 OpenAPI 문서의 자동 생성을 구하여Fastify에 손을 대보십시오

하고 싶은 일.


Node.만약 js로 API를 쓴다면 OpenAPI 문서를 자동으로 생성하기를 원합니다

배경.


API를 쓸 때 사용하는 Framework에는 파이톤에서 Django와 Flash가 유명하고, 최근 주목받는 Framework에는 FastapI가 있다.FastapI 작업은 노드입니다.js처럼 빠르고 쉽게 파악할 수 있는 특징도 있지만 코드를 쓰면 OpenAPI 문서를 자동으로 제작할 수 있고 웹 인터페이스도 준비할 수 있어 편리하다.
자세한 것을 알고 싶은 사람은 문서를 읽으세요.
https://fastapi.tiangolo.com/ja/features/
같은 일은 노드다.제이스로 하려는 API도 못 할 것 같아서 조사해봤어요.

Fastify만 쓰면 돼요.


Fastify+fastify-swagger 완료.
https://www.fastify.io
https://github.com/fastify/fastify-swagger

적당히 만든 견본


https://github.com/k-ibaraki/fastify-swagger-sample

해본 일


가져오기


fastify와fastify-swagger 설치
npm i fastify
npm i fastify-swagger

최소한의 실현


먼저 쓰기 시작하다
import * as fastify from 'fastify'
import fastifySwagger from 'fastify-swagger'

const server: fastify.FastifyInstance = fastify.fastify({ logger: true })

server.register(fastifySwagger, {
  routePrefix: '/docs',
  openapi: {},
  exposeRoute: true,
})
server.get('/ping', async (request, reply) => {
  return { pong: 'it worked!' }
})

server.listen(3000)
가 시작되고 브라우저에서 http://127.0.0.1:3000/docs에 액세스할 때 이동합니다.

조회 매개 변수를 전달해 보다


query와response를 정의하는 schema를 지정합니다.
나는 TS의 유형 정의에 푹 빠졌다.일단 움직여.나는 정확한 작법을 알고 싶다.
// queryとresponseのschemaを定義する
const schema1: fastify.RouteShorthandOptions = {
  schema: {
    querystring: {
      type: 'object',
      properties: {
        test_query: {
          type: 'number',
        },
      },
    },
    response: {
      200: {
        type: 'object',
        properties: {
          test_response: {
            type: 'number'
          },
        },
      },
    },
  },
}
// デフォルトだとqueryのTSとしての型定義がunknownなので、定義してあげる
interface Request1 extends fastify.RequestGenericInterface {
  Querystring: {
    test_query: number
  }
}
server.get<Request1, unknown, fastify.FastifySchema>('/querytest', schema1, async (request, reply) => {
  return { test_response: request.query.test_query }
})
이동

경로 매개 변수 전달 시도


질의 매개변수와 거의 동일
// paramsとresponseのschemaを定義する
const schema2: fastify.RouteShorthandOptions = {
  schema: {
    params: {
      type: 'object',
      properties: {
        test_param: {
          type: 'string',
        },
      },
    },
    response: {
      200: {
        type: 'object',
        properties: {
          test_response2: {
            type: 'string'
          },
        },
      },
    },
  },
}
// デフォルトだとParamsのTSとしての型定義がunknownなので、定義してあげる
interface Request2 extends fastify.RequestGenericInterface {
  Params: {
    test_param: string
  }
}

server.get<Request2, unknown, fastify.FastifySchema>('/paramstest/:test_param', schema2, async (request, reply) => {
  return { test_response2: request.params.test_param }
})
이동

감상

  • 느낌이 좋아요.예상한 대로 OpenAPI 문서가 자동으로 생성됩니다.
  • Fastify는express에서 사용하기 편하여 쉽게 손에 넣을 수 있지만express에 비해 대중이기 때문에 정보가 적고 괴롭습니다.특히 TS의 유형은 어렵다.좋은 작법을 몰라서 샘플을 원하지만 공식 문서는 기본적으로 JS다.
  • Fastify의 schema 정의와 TS의 유형 정의에 같은 내용을 중복적으로 썼다.쓸모없는 것 같아.형식 정의는 TS의 세계에서 이루어지길 희망합니다.
  • 그런 의미에서 NestJS를 사용하는 것이 좋을 것 같습니다.
  • 좋은 웹페이지 즐겨찾기