Search code examples
javascriptbuilder

Remove the function after it being used for the first time


I have the simple SQL query builder that looks like this:

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

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

The problem is that it returns this so I'm able to do like:

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

Is there any way to disable/remove the select function from Builder instance and autocomplete after calling it for the first time? Or to underscore that calling that function for the second time will cause an error.

Solution:

According to @Sohail answer, to make it works like that you just need to move from() from the QueryBuilder class and just return it as a field with the query as a new plain object:

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() {}
  };
}

Solution

  • You could return the specific method instead of this, that could be called in chain after this method.

    Example:

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