我正在寻找一种方法,可以传递像存储桶名称这样的值,然后使用它来填充类中我的方法中的值。我有一个 Controller ,它是一个建立两个连接的类,一个称为bucket,另一个称为bucket2。两种方法完全相同,只是一种方法使用存储桶,另一种方法使用存储桶2。我想避免创建双重方法并使用变量来决定该方法使用哪个存储桶。
下面是我的 Controller 类
const couchbase = require("couchbase")
const config = require("../config/config")
class CouchController {
constructor() {
this.cluster = new couchbase.Cluster(config.cluster);
this.cluster.authenticate(config.userid, config.password)
this.N1qlQuery = couchbase.N1qlQuery;
this.bucket = this.cluster.openBucket('Contacts', function(err) {
if (err) {
console.error('Got error: %j', err);
}
});
this.bucket2 = this.cluster.openBucket('mail_store', function(err) {
if (err) {
console.error('Got error: %j', err);
}
});
}
getDoc(docID) {
return new Promise((resolve, reject) => {
this.bucket.get(docID, (err, result) => {
if (err) return reject(err);
return resolve({ docID, result });
});
});
}
getDoc2(docID) {
return new Promise((resolve, reject) => {
this.bucket2.get(docID, (err, result) => {
if (err) return reject(err);
return resolve({ docID, result });
});
});
}
}
module.exports = CouchController
我尝试了一下并提出了一个可行的解决方案,但它并不像我想要的那样干净
getDoc(bucket, docID) {
if (bucket == "bucket2") {
bucket = this.bucket2
} else {
bucket = this.bucket
}
return new Promise((resolve, reject) => {
bucket.get(docID, (err, result) => {
if (err) return reject(err);
return resolve({ docID, result });
});
});
}
最佳答案
我想我会将存储桶对象“映射”到存储桶名称...
bucketWithName(name) {
let buckets = { bucket2: this.bucket2, ... others here ...}
return buckets[name] || this.bucket // this.bucket is default
}
getDoc(bucketName, docID) {
let bucket = this.bucketWithName(bucketName);
return new Promise((resolve, reject) => {
bucket.get(docID, (err, result) => {
if (err) return reject(err);
return resolve({ docID, result });
});
});
}
关于javascript - 传递变量来确定连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56517363/