![](/img/trans.png)
[英]How can I make variables so that I don't have to repeat myself in future functions
[英]Trying to make my functions be able to have dynamic selectors so i dont have to repeat myself
这是我的代码,我发现自己不得不为解析 json 或制作函数做很多事情。
// Adder Functions... hate repeating myself
async function addPetImagesToPet(petId, fileName) {
const pet = await db.Pet.findById(petId);
await pet.petImages.push({'fileName':fileName});
pet.updated = Date.now();
await pet.save();
//console.log(pet);
}
async function addPropertyImagesToProperty(propertyId, fileName) {
const property = await db.Property.findById(propertyId);
await property.propertyImages.push({'fileName':fileName});
property.updated = Date.now();
await property.save();
//console.log(property);
}
async function addAccountImagesToAccount(accountId, fileName) {
const account = await db.Account.findById(accountId);
await account.accountImages.push({'fileName':fileName});
account.updated = Date.now();
await account.save();
//console.log(account);
}
//how can I do `await db.${my_type/Object_Name!!! <--this is what im asking about}.findById(this obviously can be a var np)
我发现自己在我的大部分服务中重复了很多次,我试图在我的大部分服务前端和后端进一步扩展它。 如果我知道如何做到这一点,我实际上可以为每个 object 类型的大多数用例提供一个“CRUD”服务。
来了很多,一直让我疯狂解析 JSON 对象,使 object 上的选择器是动态的......
我使用 ${} 因为这就是我动态构建字符串的方式,但不能这样做或使其适用于函数或命名,例如,我不能创建一个字符串变量并将该名称用作 function 或其方法的名称,但是这正是我想要做的。 再次感谢任何能够提供帮助的人。
提前致谢。
您可以在此处执行类似的操作,使用各个值创建 hashMap。
const hashMap = {
'pet': {
dbName:"Pet",
key: 'petImages'
},
'account': {
dbName: "Account",
key: 'accountImages'
},
'property':{
dbName: "Property",
key: 'propertyImages'
}
}
async function addImagesToAccount(accountId, fileName, type) { // type will be the key for the object above.
const {dbName, key} = hashMap[type];
const account = await db[dbName].findById(accountId);
await account[key].push({'fileName':fileName});
account.updated = Date.now();
await account.save();
}
你可以使用这样的东西:
async function addImages(type, id, fileName) {
const entity = await db[type].findById(id);
entity.updated = Date.now();
const attribute = `${type.toLowerCase()}Images`;
entity[attribute].push({ fileName })
await entity.save();
}
async function main() {
await addImages('Property', 2, 'text-02');
await addImages('Account', 3, 'text-03');
await addImages('Pet', 3, 'text-03');
}
另外我认为Factory Pattern
可以帮助您编写可重用的代码:)。
理想情况下,如果您想使用更多变量,则可能是使用和数组。 保持一个不超过三个变量的函数是一种很好的做法。 但这是个人喜好。
好吧,我会用一行来做到这一点,无需将其包装在 function
await db.Pet.updateOne({ _id: petId }, { $push: : { petImages : {'fileName':fileName}}, updated: Date.now() });
谢谢大家的评论和帮助。
我的最终代码看起来像这样,当然我可以让它更短。
async function addImagesToObject(objId, objType, fileName) {
const entity = await db[`${objType}`].findById(objId);
const attribute = `${objType.toLowerCase()}Images`; //<-- defining selector
await entity[attribute].push({'fileName':fileName});
entity.updated = Date.now();
await entity.save();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.