たとえば、ユーザーを保存するRESTエンドポイントの設定を指定すると、コマンドオブジェクトのvalidate()
を使用して特定のHTTPエラーコードを取得できます応答を処理するコントローラ?Grailsコマンドオブジェクトの検証から特定のHTTPエラーコードを返す
コントローラーアクションが多くのif
ブロックを処理し、特定のエラーメッセージをチェックし、HTTPエラーコードにルックアップ/変換する必要がある状況を回避したいと考えています。
たとえば、データベース内の一致するユーザーを見つけることができなかった場合、カスタムバリデーターに何らかの方法で404を返すように指示します。
以下は私が試したことではありません。代わりに、RESTパラメータの検証に使用したい理想的な構造の概念の証明に過ぎません。おそらく、これは完全に間違っているか、より良いアプローチがあるでしょう。もしあれば、それも歓迎されるでしょう。
例:
User.groovy
...
class User {
String username
static constraints = {
username unique:true
}
}
UserController.groovy
...
class UserController extends RestfulController {
def update(UserCommand userCmd) {
/*
* Not actually working code, but proof of concept of what
* I'm trying to achieve
*/
render status: userCmd.validate()
}
class UserCommand {
Long id
String username
static constraints = {
importFrom User
/*
* I also get that you can't return Error codes via the
* custom validator, but also just to illustrate what I'm
* trying to achieve
*/
id validator: {
User user = User.get(id)
if(user == null) {
return 404
}
}
}
}
}
ありがとう、私は更新を意味した。これは有望です –
あなたの 'withUser'メソッドで 'id =" id "'パラメータを説明するいくつかのドキュメントを説明してくれますか?私はそれが何であるか分からない。 –
これは上書きできる変数です。したがって、別のパラメータでオブジェクトを検索する場合は、デフォルトの "id"ではなくidとして渡します。 – Gregg