Search code examples
javascriptperformanceelectronpouchdb

Is there a better way to check a flag and then set optional parameter in a function in javascript? (Writing function in a js object)


I just encountered this situation when i was working on an electron project. Below is a pouchDB put function where i am trying to upload an attachment with it

My current code is like this :

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,
    },
  },
  // ...
});

The problem is I want to check if the variable tAttachment is set or not. If not I don't want to add an attachment in pouchDB and in case it is set I want it as above. To do this, I would conventionally write two repeated code and add the _attachment option. I was wondering if there was a better way to do this . Something like this ? (The below won't work):

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;
      },
    },
  },
});

Solution

  • I'd probably declare the map of attachments before creating a new entity:

    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,
      // ...
    });