【问题标题】:Remove the function after it being used for the first time首次使用后删除该功能
【发布时间】:2020-07-05 19:47:47
【问题描述】:

我有一个简单的 SQL 查询生成器,如下所示:

class QueryBuilder {
  select(fields) {
    this.query = "SELECT `" + fields.join("`, `") + "` ";
    return this;
  }

  from(table) {
    this.query += "FROM `" + table + "` ";
    return this;
  }
}

问题是它返回 this 所以我可以这样做:

const sql = builder.select("field1", "field2").from("table").select("I shouldn't be able to call select");

有什么方法可以从Builder 实例中禁用/删除select 函数并在第一次调用它后自动完成?或者强调第二次调用该函数会导致错误。

解决方案:

根据@Sohail 的回答,要让它像这样工作,您只需将from()QueryBuilder 类中移出,并将其作为一个字段返回,并将查询作为一个新的普通对象:

class QueryBuilder {
  static select(fields) {
    this.query = "SELECT `" + fields.join("`, `") + "` ";
    return {
      query: this.query,
      from
    };
  }
}

function from(table) {
  this.query += "FROM `" + table + "` ";
  return {
    query: this.query,
    where: function() {}
  };
}

【问题讨论】:

    标签: javascript builder


    【解决方案1】:

    您可以返回特定的method 而不是this,这可以在此方法之后链式调用。

    示例:

    class QueryBuilder {
      select(fields) {
        this.query = "SELECT `" + fields.join("`, `") + "` ";
        return {
          from: this.from.bind(this)
        };
      }
      from(table) {
        this.query += "FROM `" + table + "` ";
        return {
          where : ""
        };
      }
    }
    

    【讨论】:

    • select()之前“不让我”打电话给from()吗?或者我只需要将它从QueryBuilder 类中移出? upd: 将其从课程中移除。您还有其他建议吗?
    • 您可以将其他方法设为私有,仅将 select 方法设为公有,但私有语法是 javascript 中的一项新功能。
    【解决方案2】:

    您可以尝试以下修改:

    select(fields) {
        if(!this.query.includes("SELECT")){
           this.query = "SELECT `" + fields.join("`, `") + "` ";
        }
        return this;
      }
    

    【讨论】:

    • 然后我仍然可以通过自动完成使用选择
    • 使用布尔标志并在第一次调用中设置为真,如果标志为真,则在第二次调用中检查相同的布尔值,返回不做任何事情。
    猜你喜欢
    • 2021-02-04
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多