Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8873

expressでOpenAPI仕様のAPIを実装するときのTips

$
0
0

要点

  1. express-openapiを使おう (openapi-generatorではなく)
  2. security handlerの実装には、シンプルにOpenAPIのinitializeメソッドに引数securityHandlersを渡すのが良い。(openapi-security-handlerは、必要ない)

express-openapiを使おう (openapi-generatorではなく)

OpenAPI仕様のYAMLファイルを Swagger Editor (https://editor.swagger.io/) などを用いて作った後、openapi-generator (https://github.com/OpenAPITools/openapi-generator) を使ってスケルトンを作れそう...と思うのですが、openapi-generatorの出力するNode.js向けのスケルトンは、あまり良い感じではないです。

むしろexpress-openapi (https://www.npmjs.com/package/express-openapi) の方が、使う機能だけ使って書くように考えられているので、やりたいことに集中できるように思います。

security handlerの実装には、シンプルにOpenAPIのinitializeメソッドに引数securityHandlersを渡すのが良い。(openapi-security-handlerは、必要ない)

APIサーバを実装するとき、ほとんどの場合、セキュリティのことも考えることになると思います。

このとき、express-openapiのHighlightsを見ると、こういうことが記述されています。

Leverages security definitions for security management.
* See openapi-security-handler

openapi-security-handlerを使う必要があるのかな...と感じますが、必要ありません。

express-openapiでセキィリティハンドラを実装するときは、initializeメソッドの引数secuurityHandlersを渡すのが正解です。

initialize({apiDoc:apiDoc,app:app,securityHandlers:{keyScheme:function(req,scopes){returnPromise.resolve(true);}}});

reqはexpressでおなじみのもので、scopesには、以下のようにAPIの定義のsecurityでスキーマ別に定義するスコープ配列が渡ってきます。

security:-keyScheme:[admin]

セキュリティハンドラの戻り値は、即値でbooleanを返すか、booleanを返すPromiseとします。

trueが認証OKで、falseがNGです。


Viewing all articles
Browse latest Browse all 8873

Trending Articles