Skip to content

スキーマ定義

このページでは、JSDocコメントでスキーマを定義する方法を学びます。

説明

JSDocコメントでスキーマを説明できます。

ts
/** Bookスキーマ情報 */
interface Book {
  /** 本のID */
  id: number;
  /** 本のタイトル */
  title: string;
}
生成されたOpenAPI仕様
yaml
components:
  schemas:
    Book:
      description: Bookスキーマ情報
      type: object
      properties:
        id:
          type: number
          description: 本のID
        title:
          type: string
          description: 本のタイトル
      required:
        - id
        - title

スキーマに例を追加するには、@exampleタグを使用できます。

ts
interface Book {
  /**
   * 本のID
   * @example 123456789
   * */
  id: number;
  /**
   * 本のタイトル
   * @example グレート・ギャツビー
   */
  title: string;
}
生成されたOpenAPI仕様
yaml
components:
  schemas:
    Book:
      type: object
      properties:
        id:
          type: number
          description: 本のID
          example: 123456789
        title:
          type: string
          description: 本のタイトル
          example: グレート・ギャツビー
      required:
        - id
        - title

フォーマット

スキーマのフォーマットを指定するには、Tspecが提供するユーティリティ型を使用できます。

ts
import { Tspec } from 'tspec';

interface Book {
  id: Tspec.Integer;
  coverImage: Tspec.ImageUriString;
  publishedAt: Tspec.DateTimeString;
}
生成されたOpenAPI仕様
yaml
components:
  schemas:
    Book:
      type: object
      properties:
        id:
          type: integer
          example: 1
        coverImage:
          format: uri
          type: string
          example: https://picsum.photos/200/300
        publishedAt:
          format: date-time
          type: string
          example: '2023-03-30T12:00:00Z'
      additionalProperties: false
      required:
      - coverImage
      - id
      - publishedAt

Tspecが提供するユーティリティ型は以下の通りです。

説明
Tspec.Integer整数
Tspec.DateString日付文字列(例:2021-01-01
Tspec.DateTimeString日付時刻文字列(例:2021-01-01T00:00:00Z
Tspec.PasswordStringパスワード文字列(例:password
Tspec.ByteStringバイト文字列(例:dGVzdA==
Tspec.BinaryStringバイナリ文字列(例:0x1234
Tspec.BinaryStringArrayバイナリ文字列配列(例:[0x1234, 0x5678]
Tspec.EmailStringメール文字列(例:test@test.com
Tspec.UuidStringUUID文字列(例:123e4567-e89b-12d3-a456-426614174000
Tspec.UrlStringURL文字列(例:http://localhost
Tspec.ImageUriString画像URI文字列(例:https://picsum.photos/200/300
Tspec.HostnameStringホスト名文字列(例:localhost
Tspec.Ipv4StringIPv4文字列(例:127.0.0.1
Tspec.Ipv6StringIPv6文字列(例:::1
Tspec.JsonPointerStringJSON Pointer文字列(例:/