FC2 ブログ

ぎじゅつのメモ

OpenAPI Generatorで踏んだバグたち

背景

現在所属しているチームでOpenAPI Specification 2.0(Swagger2.0)で記述されたAPI仕様書が放置されていた。
これをOpenAPI Generatorを利用してTypeScript向けのAPIクライアントのコードを自動生成したかった。(利用しようとしたOpenAPI Generatorのバージョンは4.0.3)
(OpenAPI Specification 3.0 にマイグレーション済み。)

踏んだ罠たちの書き殴り

OpenAPI Specification2.0から3.0にマイグレーション完了した!ので、コード自動生成してみるかー

components.requestBodies を定義すると壊れたコードが生成される

The following schema has undefined (null) baseType. It could be due to form parameter defined in OpenAPI v2 spec with incorrect consumes. A correct 'consumes' for form parameters should be 'application/x-www-form-urlencoded' or 'multipart/form-data'

とエラーが吐かれ、リクエストボディの中身が `UNKNOWN_BASE_TYPE` になってる

github.com

github.com

components:
    requestBodys:
      HogeRequestBody: ...

みたいにcomponents.requestBodiesを直接指定するのがアカンらしく

components:
    schema:
      Hoge: ...

components.schemasにスキーマを抽出してやって妥協するしかなさそう

oneOfを使うと壊れたコードが生成される

こういうやつ

hogeIndex:
    oneOf:
        - type: integer
        - type: string
    enum:
        - 0
        - 1
        - 2
        - user

この辺 github.com

github.com

諦めてこうした

hogeIndex:
    type: string
    enum:
        - 0
        - 1
        - 2
        - user

allOf を使っても壊れるという噂 oneOf と allOf は当面避けれるなら避けたほうが良さそう(OpenAPI Generatorが直ることを祈ろう)

application/x-www-form-urlencoded で requestBody に Collection を指定するとぶっ壊れる

ちゃんと名前空間が指定されてなくて、未定義変数を参照してるってなって壊れてるやつ

github.com

マジかよ...

application/x-www-form-urlencoded で パラメータのシリアライズがそんなにうまくいかない

パラメータのシリアライズとはこの辺の話 github.com

https://github.com/OpenAPITools/openapi-generator/blob/v4.0.3/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java#L4525

↑requestBodyでパラメータが配列のときhoge=fuga&hoge=piyo みたいな指定できない。
強制的にcollectionFormatが "csv" hoge=fuga,piyo みたいなカンマ区切りになる。
そんでもってrequestBodyではPHP特有の hoge[fuga]=piyo がまだ考慮されてなさそう(そんなAPIのインタフェースをやめたほうがいい)

具体的にどういうことかというと

requestBody:
    content:
      application/x-www-form-urlencoded:
        schema:
          type: object
          properties:
            hoge:
              type: array
              items:
                type: string
        encoding:
          hoge:
            style: form
            explode: true

としたとき、

先述したcollectionFormatがcsv固定になってしまってるので

この分岐に入ることができず
https://github.com/OpenAPITools/openapi-generator/blob/v4.0.3/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java#L3073-L3075

isCollectionFormatMultiが立たないから
https://github.com/OpenAPITools/openapi-generator/blob/v4.0.3/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache#L158-L162

そして問題の

application/x-www-form-urlencoded で requestBody に Collection を指定するとぶっ壊れる

https://github.com/OpenAPITools/openapi-generator/blob/v4.0.3/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache#L164

に入る
以上。詰み。

github.com query parameterは対応しているのは見た

そんなネストしたオブジェクトをリクエストボディで送りたいならJSONを使えという話である

とりあえず、壊れてないコードを生成することができるまでになった。
OpenAPI Generatorバグバグだけど、乗り越えられるとやっぱコードの自動生成サイコーという気持ちになります。