【发布时间】: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