【问题标题】:Verify that a JSON object properties are contained in an Enum验证 JSON 对象属性是否包含在 Enum 中
【发布时间】:2021-11-20 15:33:55
【问题描述】:

我有一个 Lambda HTTPS TS 函数,它获取从前端传递给它的 JSON 对象。我想对那个 JSON 对象做一些验证

正文应该有这个形状(通知):

interface Notifications {
  type: NotificationType;
  frequency: FrequencyType;
}

enum NotificationType {
  SMS = 'SMS',
  EMAIL = 'EMAIL'
}

enum FrequencyType {
  INSTANT = 'INSTANT',
  DAILY = 'DAILY',
  WEEKLY = 'WEEKLY',
  NEVER = 'NEVER'
}

我现在从另一个 stack post 那里得到的东西不起作用

  if (body && body.frequency in FrequencyType && body.type in NotificationType) {
//do stuff
}

有没有更简洁的方法来确认前端永远不会传递无效的通知类型?我确实在 FE 上使用了 Typing,但也只是尝试在后端处理验证

TS 到 JS 代码在枚举中遵循这一点

   var NotificationType;

(function(NotificationType2) {

  NotificationType2["SMS"] = "SMS";

  NotificationType2["EMAIL"] = "EMAIL";

})(NotificationType || (NotificationType = {}));

var FrequencyType;

(function(FrequencyType2) {

  FrequencyType2["INSTANT"] = "INSTANT";

  FrequencyType2["DAILY"] = "DAILY";

  FrequencyType2["WEEKLY"] = "WEEKLY";

  FrequencyType2["NEVER"] = "NEVER";

})(FrequencyType || (FrequencyType = {}));

【问题讨论】:

    标签: javascript json typescript


    【解决方案1】:

    TS 代码

    enum NotificationType {
      SMS = 'SMS',
      EMAIL = 'EMAIL'
    }
    
    enum FrequencyType {
      INSTANT = 'INSTANT',
      DAILY = 'DAILY',
      WEEKLY = 'WEEKLY',
      NEVER = 'NEVER'
    }
    
    type BodyType =  {
        frequency: NotificationType;
        type: NotificationType
    }
    
    const validate = (body:BodyType):boolean => !!body && body.frequency in FrequencyType && body.type in NotificationType; 
    

    编译TS后 验证代码应该可以正常工作

    validate({ frequency: 'INSTANT', type: 'SMS' }); // true
    validate({}); // false
    validate({ frequency: 'INSTANTS', type: 'SMS' }); // false
    

    检查您是否需要 OR 条件。

    !!body && (body.frequency in FrequencyType || body.type in NotificationType)
    

    【讨论】:

      【解决方案2】:

      所以前端在错误的情况下传递了 JSON 对象的键,我的 //doStuff 代码也在运行一个对这个用户不起作用的 SQL PUT,因为他们在数据库中没有记录所以不得不重新工作一下

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-27
        • 1970-01-01
        • 2018-05-01
        • 2020-10-15
        • 2017-06-11
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        相关资源
        最近更新 更多