2
0

More than 1 year has passed since last update.

Spectralでパスが小文字英数字のみかをチェックするルール

Posted at

この投稿では、Spectral を使って、OpenAPI パスのキーに小文字の英数字しか使われていないかどうかをチェックする方法を紹介します。

Spectral とは?

Spectralは、ルールベースのJSON/YAMLリンターです。どんなJSON/YAMLもチェックできますが、特にOpenAPI用に設計されています。

問題点

複数の単語を含むパスを表現する場合、キャメルケース、ケバブケース、アンダースコアなど、いくつかの形式の選択肢があります。

GET /pullRequests/{id}
GET /pull-requests/{id}
GET /pull_requests/{id}
GET /pullrequests/{id}

チームで共同作業を行う場合、API設計規約でどの形式を選択すべきかを定義しておく必要があります。

しかし、人々はしばしば間違いを犯します。規約を知らなかったり、注意深く読んでいなかったりします。

解決策 Spectralでパス規約をチェックする

この問題を解決するためには、Spectralでチェックを自動化することが有効です。

パスが全て小文字の英数字であるかどうかをチェックするための、Spectralのルールは次のようになります。これを.spectral.ymlに記述します。

extends: spectral:oas
rules:
  path-keys-lower-case-alphanumeric:
    message: "Path must be lower case. Only lower case alphanumeric characters are allowed."
    given: "$.paths"
    then:
      field: "@key"
      function: pattern
      functionOptions:
        match: "^(?:\\{[^}]+\\}|[/a-z\\d])*$" # https://regex101.com/r/eHmZ29/1

このルールを追加することで、Spectralはパスに大文字やハイフンが含まれる場合に警告を出すようになります。

$ npx spectral lint openapi-spec.yaml
/path/to/my/openapi-spec.yaml
 17:15  warning  path-keys-lower-case-alphanumeric  Path must be lower case. Only lower case alphanumeric characters are allowed.  paths./pullRequests
 27:23  warning  path-keys-lower-case-alphanumeric  Path must be lower case. Only lower case alphanumeric characters are allowed.  paths./pull-requests

✖ 2 problems (0 errors, 2 warnings, 0 infos, 0 hints)

ルールの詳細

上で紹介したルールは、Spectralのコア関数[pattern]を使用しています。この関数は、与えられたフィールドが正規表現にマッチするかどうかをチェックします。

正規表現 ^(?:\{[^}]+\}|[/a-z\d])*$ は、パスが小文字の英数字のみを含むかどうかをチェックする正規表現です。この表現は以下の文字列にマッチします。

/
/foo
/123
/foobar
/foo123
/{foo}
/{fooBar}
/{foo_bar}
/{foo-bar}
/users
/users/{userId}
/users/{user-id}
/users/{userid}
/users/{user_id}

一方、以下の文字列は禁止されます。

/Foo
/fooBar
/foo-bar
/foo_bar
/temas/{teamId}/MEMBERS/{userId}
2
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
2
0