# Requestに適正な値が入ってなかったら400エラーを返す

[該当のPR](https://github.com/weseek/growi/pull/1554)

 Global Notification 設定の POST api 作成時のレビューです。
 
 
## レビュー

notifyToType の値が mail になるか slack になるかによって処理を変えていました。  
 switch を使用して、notifyToType に適正な値が入ってなかったらエラーを返す想定でした。
 
しかし、ここで返さなければいけないのは [エラーコード 400](https://tips.weseek.co.jp/5e50e732839fe70048321586) です。  
> HyperText Transfer Protocol (HTTP) の 400 Bad Request レスポンスステータスコードは、何らかのクライアント側のエラーであると分かったために、サーバーがそのリクエストを処理しない (できない) ことを表します[^1]

そして、400 エラーを返すのは[バリデーション](/用語集/バリデーション)の責務です。

```javascript:notification-setting.js
const validator = {
  slackConfiguration: [
    body('webhookUrl').isString().trim(),
    body('isIncomingWebhookPrioritized').isBoolean(),
    body('slackToken').isString().trim(),
  ],
  userNotification: [
    body('pathPattern').isString().trim(),
    body('channel').isString().trim(),
  ],
  globalNotification: [
    body('triggerPath').isString().trim().not()
      .isEmpty(),
    body('notifyToType').isString().trim().isIn(['mail', 'slack']),
    body('toEmail').trim().custom((value, { req }) => {
      return (req.body.notifyToType === 'mail') ? (!!value && value.match(/.+@.+\..+/)) : true;
    }),
    body('slackChannels').trim().custom((value, { req }) => {
      return (req.body.notifyToType === 'slack') ? !!value : true;
    }),
  ],
};
```

validator に globalNotification 追加しました。

Validation Chain である `isIn(['mail','slack'])` を使用して notifyToType の値が正しいかチェックしています。  
また、 notifyToType の値に応じた[カスタムバリデーター](/用語集/Express/express-validator)も使用しています。  

今後 Twitter 通知などで機能を追加するときはバリデーターも修正する必要がありそうです。



[^1]: https://developer.mozilla.org/ja/docs/Web/HTTP/Status/400

---

## Page Navigation

- Canonical URL: https://tips.weseek.co.jp/今日のレビューから/Requestに適正な値が入ってなかったら400エラーを返す
- Permalink: https://tips.weseek.co.jp/5e38f144e848c600487d69a5
- Parent: [今日のレビューから](/5e38deb8e848c600487d69a0.md)
- Children: 0 total
- Total descendants: 0
- Siblings: 4 total
  - [routerとserviceの責務](/5f323bfc55d58b0048c43b00.md)
  - [それって車輪の再発明じゃない？](/5e425d62decd0a0049953aef.md)
  - [イテレータを利用してスマートな実装しよう](/5e3f9b11f5921400485be6ad.md)
  - [関数名定義(getHoge)](/5f4883eb0802bb00498f41d9.md)
- Last updated: 2020-02-24T11:01:43.753Z by deleted_at_1672138397219
- Full page listing (all children regardless of count): https://tips.weseek.co.jp/_api/v3/page-listing/children?id=5e38f144e848c600487d69a5
