LoginSignup
3
0

More than 3 years have passed since last update.

OpenAPI Generator で Deno クライアントの生成が可能になりました

Last updated at Posted at 2020-07-01

OpenAPI GeneratorDeno クライアントの生成が可能になりました。
私が PR を作成し無事?マージされました。
使い方についてご紹介したいと思います。

openapi-generator-cli のダウンロード

まずは、openapi-generator-cli をダウンロードします。
せっかくなので? deno コマンドでダウンロードしてみます。

$ deno eval 'fetch("https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.1/openapi-generator-cli-5.0.1.jar").then(r=>r.arrayBuffer()).then(b=>Deno.writeFile("openapi-generator-cli.jar",new Uint8Array(b)))'

コードの生成

openapi-generator-cli は、Java で作成されていますので、JDK がインストールされている必要があります。
次のコマンドでクライアントコードを生成します。
--additional-propertiesplatformdeno が指定できるようになっています。

$ java -jar openapi-generator-cli.jar generate -i https://petstore.swagger.io/v2/swagger.json -g typescript --additional-properties=platform=deno -o generated-src

generated-src ディレクトリ配下にファイルが生成されます。

生成されたコードの利用

次の内容で test.ts というファイルを作成します。

import * as petstore from "./generated-src/index.ts";

const configuration = petstore.createConfiguration();
const petApi = new petstore.PetApi(configuration);
const pets = await petApi.findPetsByStatus(["available"]); // status が available のデータを取得します
console.log(pets.slice(0, 5)); // レスポンスの最初の5件だけ表示

次のコマンドで実行します。
ホスト petstore.swagger.io の API を利用しています。

deno run --allow-net=petstore.swagger.io test.ts

実行結果は、以下のようになります。

[
  Pet {
    id: 1245,
    category: Category { id: 1245, name: "xyz" },
    name: "xyz",
    photoUrls: [ "test" ],
    tags: [],
    status: "available"
  },
  Pet {
    id: 112256,
    category: Category { id: 0, name: "dog" },
    name: "Rex",
    photoUrls: [ "http://example.com/images/rex.png" ],
    tags: [],
    status: "available"
  },
  Pet {
    id: 112258,
    category: Category { id: 0, name: "dog" },
    name: "Rex",
    photoUrls: [ "http://example.com/images/rex.png" ],
    tags: [],
    status: "available"
  },
  Pet {
    id: 12121,
    category: Category { id: 0, name: "string" },
    name: "TestPetName",
    photoUrls: [ "string" ],
    tags: [ Tag { id: 0, name: "string" } ],
    status: "available"
  },
  Pet {
    id: 112270,
    category: Category { id: 0, name: "dog" },
    name: "Rex",
    photoUrls: [ "http://example.com/images/rex.png" ],
    tags: [],
    status: "available"
  }
]

おわりに

生成されたコードは、Deno の fetch API を利用しています。
正直なところ、 fetch API だと機能不足であり、もうちょっと高機能な HTTP クライアントが Deno に標準で入らないかなーと思っているところです。

以上です。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0