有没有更好的方法来检查标志,然后在 javascript 中的函数中设置可选参数? (在js对象中写入函数)

时间:2020-12-24 13:49:39

标签: javascript performance electron pouchdb

我刚刚在做一个电子项目时遇到了这种情况。下面是一个 pouchDB put 函数,我试图用它上传附件

我目前的代码是这样的:

testCasesDB.put({
  _id: String(info.doc_count),
  collectionID: String(collectionID),
  name: String(tName),
  description: String(tDescription),
  performed: tPerform,
  added: tAdd,
  _attachments: {
    testCaseFile: {
      type: tAttachment.type,
      data: tAttachment,
    },
  },
  // ...
});

问题是我想检查是否设置了变量 tAttachment。如果不是,我不想在 pouchDB 中添加附件,如果它被设置,我想要它如上。为此,我通常会编写两个重复的代码并添加 _attachment 选项。我想知道是否有更好的方法来做到这一点。像这样的东西? (以下不起作用):

testCasesDB.put({
  _id: String(info.doc_count),
  collectionID: String(collectionID),
  name: String(tName),
  description: String(tDescription),
  performed: tPerform,
  added: tAdd,
  _attachments: {
    testCaseFile: {
      function() {
        if (tAttachment) {
          returnData = {
            type: tAttachment.type,
            data: tAttachment,
          };
        } else {
          returnData = null;
        }
        return returnData;
      },
    },
  },
});

1 个答案:

答案 0 :(得分:0)

我可能会在创建新实体之前声明附件映射:

const attachments = {};

if (tAttachment) {
  attachments.testCaseFile =  {
    type: tAttachment.type,
    data: tAttachment,
  }
}

testCasesDB.put({
  _id: String(info.doc_count),
  collectionID: String(collectionID),
  name: String(tName),
  description: String(tDescription),
  performed: tPerform,
  added: tAdd,
  _attachments: attachments,
  // ...
});
相关问题