【问题标题】:Something wrong with If...elseIf...else 有问题
【发布时间】:2020-05-28 13:12:54
【问题描述】:

我有这个user.model

// user.model.ts

interface User {
  name: string
  email: string
  password: string
  is_active: boolean
}

我会在使用电子邮件注册之前检查电子邮件是否被占用并且用户是否处于活动状态。

    // If email is taken and is_active is true
    if (found && found.is_active) {
      return next(Boom.badRequest('Email is taken'))
    } else if (found && !found.is_active) {
      // If email is taken and is_active is false, ask to signin
      return next(Boom.unauthorized('Please signin to activate'))
    } else {
      const created = await service.create(data)
      res.send('OK')
    }

但问题是,当我尝试使用已注册并处于活动状态的电子邮件 (some@one.com) 时,它显示 Email is taken 是正确的。然后,当我尝试使用另一封 已注册但未激活的电子邮件 (any@one.com) 时,它尝试插入数据并破坏服务器,因为 email 列是 unique 是数据库(Postgres)。

我又试了一次,但这次是 (any@one.com) 第一和 (some@one.com) 第二。它在第二种情况下再次破裂。

我想问题是它只适用于一种情况。

我也试过switch...case,也不起作用。

    switch (true) {
      case found && found.is_active:
        // If email is taken and is_active is true
        return next(Boom.badRequest('Email is taken'))
      case found && !found.is_active:
        // If email is taken and is_active is false, ask to signin
        return next(Boom.unauthorized('Please signin to activate'))
      default: {
        const created = await service.create(data)
        res.send('OK')
      }
    }

请帮忙,我该如何解决这个问题?

【问题讨论】:

  • 我不明白这个问题。如果您使用已注册的电子邮件进行注册,它显然会显示“电子邮件已被占用”。
  • 你查看found有哪些数据了吗?
  • @ZainZafar 这是 javascript 中的一种合法技术。评估为 true 的 case 语句将运行。
  • 这些ifs/switches的简单逻辑没有错。鉴于found && found.is_activefound && !found.is_active 耗尽了found 为真(存在)的逻辑可能性,那么逻辑上“找到”一定是假的。所以问题出在你提供的代码之外。
  • 所以无法找到未激活的电子邮件?考虑到您提供的代码,您应该检查您找到的逻辑。

标签: javascript node.js typescript


【解决方案1】:

你为什么要这样使用if 语句?

if (found) {
  if (found.is_active) {
    // already in use by active user
    return next(Boom.badRequest('Email is taken'))
  } else {
   // in use, but inactive
   return next(Boom.unauthorized('Please signin to activate'))
  }
else {
// not found, must create
  const created = await service.create(data)
  res.send('OK')
}

【讨论】:

  • 这只是样式的改变,逻辑是一样的。为什么它会解决任何问题?
  • 它排除了它是格式错误的 if 语句的可能性。
  • 我们可以看到它不是。 if 语句的逻辑 是正确的。因此,问题出在其他地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
  • 2021-05-15
相关资源
最近更新 更多