Express.js handler to update user fieldsExpress.js controller with Node.js style exports.methodsRoutes for a...

What does Cypher mean when he says Neo is "gonna pop"?

Is it a fallacy if someone claims they need an explanation for every word of your argument to the point where they don't understand common terms?

insert EOF statement before the last line of file

Every character has a name - does this lead to too many named characters?

Why does String.replaceAll() work differently in Java 8 from Java 9?

Why avoid shared user accounts?

What to do when being responsible for data protection in your lab, yet advice is ignored?

How should I handle players who ignore the session zero agreement?

How to acknowledge an embarrassing job interview, now that I work directly with the interviewer?

Why is working on the same position for more than 15 years not a red flag?

How would one buy a used TIE Fighter or X-Wing?

Can a dragon be stuck looking like a human?

Quenching swords in dragon blood; why?

Explain the objections to these measures against human trafficking

Should I write a companion book/blog?

Why doesn't "auto ch = unsigned char{'p'}" compile under C++ 17?

Would a National Army of mercenaries be a feasible idea?

How to avoid being sexist when trying to employ someone to function in a very sexist environment?

What kind of hardware implements Fourier transform?

What makes the Forgotten Realms "forgotten"?

Disable the ">" operator in Rstudio linux terminal

Am I a Rude Number?

Can we use the stored gravitational potential energy of a building to produce power?

How do I say "Brexit" in Latin?



Express.js handler to update user fields


Express.js controller with Node.js style exports.methodsRoutes for a user controller in a Node.js applicationParsing a CSV file in node.js and express.jsRESTful backend API for user accountExpress.js MVC controller routerNodeJS controllers for a bus and a userPulling behavior from middleware for unit testing express.jsUser authentication using PassportFetching user details, posts, and comments using promises in ExpressJSExpress.js routes management for large web application













1












$begingroup$


I have an express handler which i thought was pretty simple, but CodeClimate flagged this method as having a Cognitive complexity of 6 (5 is the max by default without flagging something)



Curious how I could simplify this method to reduce Cognitive complexity.



function updateUser (req, res) {
// Update any fields that were passed in.
// Explicitly checking for undefined b/c passing null values should set them to null in the db
if (req.body.firstName !== undefined) {
req.user.firstName = req.body.firstName
}

if (req.body.lastName !== undefined) {
req.user.lastName = req.body.lastName
}

if (req.body.email !== undefined) {
req.user.email = req.body.email
}

if (req.body.phone !== undefined) {
req.user.phone = req.body.phone
}

if (req.body.fax !== undefined) {
req.user.fax = req.body.fax
}

if (req.body.notes !== undefined) {
req.user.notes = req.body.notes
}

req.user.save()
.then(user => {
return res.status(HttpStatus.OK).send(user)
})
.catch(err => {
req.log.error(err)
return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message)
})
}









share|improve this question









New contributor




Catfish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 1




    $begingroup$
    Cognitive complexity or cyclomatic complexity (as in the added tag)?
    $endgroup$
    – Alexei
    yesterday
















1












$begingroup$


I have an express handler which i thought was pretty simple, but CodeClimate flagged this method as having a Cognitive complexity of 6 (5 is the max by default without flagging something)



Curious how I could simplify this method to reduce Cognitive complexity.



function updateUser (req, res) {
// Update any fields that were passed in.
// Explicitly checking for undefined b/c passing null values should set them to null in the db
if (req.body.firstName !== undefined) {
req.user.firstName = req.body.firstName
}

if (req.body.lastName !== undefined) {
req.user.lastName = req.body.lastName
}

if (req.body.email !== undefined) {
req.user.email = req.body.email
}

if (req.body.phone !== undefined) {
req.user.phone = req.body.phone
}

if (req.body.fax !== undefined) {
req.user.fax = req.body.fax
}

if (req.body.notes !== undefined) {
req.user.notes = req.body.notes
}

req.user.save()
.then(user => {
return res.status(HttpStatus.OK).send(user)
})
.catch(err => {
req.log.error(err)
return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message)
})
}









share|improve this question









New contributor




Catfish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$








  • 1




    $begingroup$
    Cognitive complexity or cyclomatic complexity (as in the added tag)?
    $endgroup$
    – Alexei
    yesterday














1












1








1





$begingroup$


I have an express handler which i thought was pretty simple, but CodeClimate flagged this method as having a Cognitive complexity of 6 (5 is the max by default without flagging something)



Curious how I could simplify this method to reduce Cognitive complexity.



function updateUser (req, res) {
// Update any fields that were passed in.
// Explicitly checking for undefined b/c passing null values should set them to null in the db
if (req.body.firstName !== undefined) {
req.user.firstName = req.body.firstName
}

if (req.body.lastName !== undefined) {
req.user.lastName = req.body.lastName
}

if (req.body.email !== undefined) {
req.user.email = req.body.email
}

if (req.body.phone !== undefined) {
req.user.phone = req.body.phone
}

if (req.body.fax !== undefined) {
req.user.fax = req.body.fax
}

if (req.body.notes !== undefined) {
req.user.notes = req.body.notes
}

req.user.save()
.then(user => {
return res.status(HttpStatus.OK).send(user)
})
.catch(err => {
req.log.error(err)
return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message)
})
}









share|improve this question









New contributor




Catfish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




I have an express handler which i thought was pretty simple, but CodeClimate flagged this method as having a Cognitive complexity of 6 (5 is the max by default without flagging something)



Curious how I could simplify this method to reduce Cognitive complexity.



function updateUser (req, res) {
// Update any fields that were passed in.
// Explicitly checking for undefined b/c passing null values should set them to null in the db
if (req.body.firstName !== undefined) {
req.user.firstName = req.body.firstName
}

if (req.body.lastName !== undefined) {
req.user.lastName = req.body.lastName
}

if (req.body.email !== undefined) {
req.user.email = req.body.email
}

if (req.body.phone !== undefined) {
req.user.phone = req.body.phone
}

if (req.body.fax !== undefined) {
req.user.fax = req.body.fax
}

if (req.body.notes !== undefined) {
req.user.notes = req.body.notes
}

req.user.save()
.then(user => {
return res.status(HttpStatus.OK).send(user)
})
.catch(err => {
req.log.error(err)
return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message)
})
}






javascript node.js express.js cyclomatic-complexity






share|improve this question









New contributor




Catfish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Catfish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited yesterday









200_success

130k16153417




130k16153417






New contributor




Catfish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









CatfishCatfish

1062




1062




New contributor




Catfish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Catfish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Catfish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 1




    $begingroup$
    Cognitive complexity or cyclomatic complexity (as in the added tag)?
    $endgroup$
    – Alexei
    yesterday














  • 1




    $begingroup$
    Cognitive complexity or cyclomatic complexity (as in the added tag)?
    $endgroup$
    – Alexei
    yesterday








1




1




$begingroup$
Cognitive complexity or cyclomatic complexity (as in the added tag)?
$endgroup$
– Alexei
yesterday




$begingroup$
Cognitive complexity or cyclomatic complexity (as in the added tag)?
$endgroup$
– Alexei
yesterday










2 Answers
2






active

oldest

votes


















1












$begingroup$

Assignments can be contracted to something like below:



 req.user.firstName = req.body.firstName || req.user.firstName;
req.user.lastName = req.body.lastName || req.user.lastName;
req.user.email = req.body.email || req.user.email;
req.user.phone = req.body.phone || req.user.phone;
req.user.fax = req.body.fax || req.user.fax;
req.user.notes = req.body.notes || req.user.notes;


I think it can further be reduced if properties are put in some array and iterated over (since source and destination property have the same name), but I would stick with this arguably more readable text.



I am not familiar with express.js, so the following might not be applicable (I usually work with Typescript in Angular).



Your request have both a body and some user property. It is recommended to clearly separate output from input in order to obtain pure functions as much as possible. Something like below:



 updateUserFromRequest(req, user) {

// clone to avoid changing provided reference
var ret = [... user];

// assignment logic here using ret

return ret;
}





share|improve this answer









$endgroup$





















    1












    $begingroup$

    If you are using Mongoose, another possibility is to simply use your model validation to check if required data are present or not.



    Then it will give you something like this:



    function updateUser (req, res) {
    req.user.set(req.body);
    req.user.save()
    //... Then catch and handle validation error :)
    }


    More info on .set() method.

    More info on model validation.






    share|improve this answer








    New contributor




    laudeon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






    $endgroup$













      Your Answer





      StackExchange.ifUsing("editor", function () {
      return StackExchange.using("mathjaxEditing", function () {
      StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
      StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
      });
      });
      }, "mathjax-editing");

      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "196"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });






      Catfish is a new contributor. Be nice, and check out our Code of Conduct.










      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214496%2fexpress-js-handler-to-update-user-fields%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1












      $begingroup$

      Assignments can be contracted to something like below:



       req.user.firstName = req.body.firstName || req.user.firstName;
      req.user.lastName = req.body.lastName || req.user.lastName;
      req.user.email = req.body.email || req.user.email;
      req.user.phone = req.body.phone || req.user.phone;
      req.user.fax = req.body.fax || req.user.fax;
      req.user.notes = req.body.notes || req.user.notes;


      I think it can further be reduced if properties are put in some array and iterated over (since source and destination property have the same name), but I would stick with this arguably more readable text.



      I am not familiar with express.js, so the following might not be applicable (I usually work with Typescript in Angular).



      Your request have both a body and some user property. It is recommended to clearly separate output from input in order to obtain pure functions as much as possible. Something like below:



       updateUserFromRequest(req, user) {

      // clone to avoid changing provided reference
      var ret = [... user];

      // assignment logic here using ret

      return ret;
      }





      share|improve this answer









      $endgroup$


















        1












        $begingroup$

        Assignments can be contracted to something like below:



         req.user.firstName = req.body.firstName || req.user.firstName;
        req.user.lastName = req.body.lastName || req.user.lastName;
        req.user.email = req.body.email || req.user.email;
        req.user.phone = req.body.phone || req.user.phone;
        req.user.fax = req.body.fax || req.user.fax;
        req.user.notes = req.body.notes || req.user.notes;


        I think it can further be reduced if properties are put in some array and iterated over (since source and destination property have the same name), but I would stick with this arguably more readable text.



        I am not familiar with express.js, so the following might not be applicable (I usually work with Typescript in Angular).



        Your request have both a body and some user property. It is recommended to clearly separate output from input in order to obtain pure functions as much as possible. Something like below:



         updateUserFromRequest(req, user) {

        // clone to avoid changing provided reference
        var ret = [... user];

        // assignment logic here using ret

        return ret;
        }





        share|improve this answer









        $endgroup$
















          1












          1








          1





          $begingroup$

          Assignments can be contracted to something like below:



           req.user.firstName = req.body.firstName || req.user.firstName;
          req.user.lastName = req.body.lastName || req.user.lastName;
          req.user.email = req.body.email || req.user.email;
          req.user.phone = req.body.phone || req.user.phone;
          req.user.fax = req.body.fax || req.user.fax;
          req.user.notes = req.body.notes || req.user.notes;


          I think it can further be reduced if properties are put in some array and iterated over (since source and destination property have the same name), but I would stick with this arguably more readable text.



          I am not familiar with express.js, so the following might not be applicable (I usually work with Typescript in Angular).



          Your request have both a body and some user property. It is recommended to clearly separate output from input in order to obtain pure functions as much as possible. Something like below:



           updateUserFromRequest(req, user) {

          // clone to avoid changing provided reference
          var ret = [... user];

          // assignment logic here using ret

          return ret;
          }





          share|improve this answer









          $endgroup$



          Assignments can be contracted to something like below:



           req.user.firstName = req.body.firstName || req.user.firstName;
          req.user.lastName = req.body.lastName || req.user.lastName;
          req.user.email = req.body.email || req.user.email;
          req.user.phone = req.body.phone || req.user.phone;
          req.user.fax = req.body.fax || req.user.fax;
          req.user.notes = req.body.notes || req.user.notes;


          I think it can further be reduced if properties are put in some array and iterated over (since source and destination property have the same name), but I would stick with this arguably more readable text.



          I am not familiar with express.js, so the following might not be applicable (I usually work with Typescript in Angular).



          Your request have both a body and some user property. It is recommended to clearly separate output from input in order to obtain pure functions as much as possible. Something like below:



           updateUserFromRequest(req, user) {

          // clone to avoid changing provided reference
          var ret = [... user];

          // assignment logic here using ret

          return ret;
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered yesterday









          AlexeiAlexei

          1,452729




          1,452729

























              1












              $begingroup$

              If you are using Mongoose, another possibility is to simply use your model validation to check if required data are present or not.



              Then it will give you something like this:



              function updateUser (req, res) {
              req.user.set(req.body);
              req.user.save()
              //... Then catch and handle validation error :)
              }


              More info on .set() method.

              More info on model validation.






              share|improve this answer








              New contributor




              laudeon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.






              $endgroup$


















                1












                $begingroup$

                If you are using Mongoose, another possibility is to simply use your model validation to check if required data are present or not.



                Then it will give you something like this:



                function updateUser (req, res) {
                req.user.set(req.body);
                req.user.save()
                //... Then catch and handle validation error :)
                }


                More info on .set() method.

                More info on model validation.






                share|improve this answer








                New contributor




                laudeon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                $endgroup$
















                  1












                  1








                  1





                  $begingroup$

                  If you are using Mongoose, another possibility is to simply use your model validation to check if required data are present or not.



                  Then it will give you something like this:



                  function updateUser (req, res) {
                  req.user.set(req.body);
                  req.user.save()
                  //... Then catch and handle validation error :)
                  }


                  More info on .set() method.

                  More info on model validation.






                  share|improve this answer








                  New contributor




                  laudeon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.






                  $endgroup$



                  If you are using Mongoose, another possibility is to simply use your model validation to check if required data are present or not.



                  Then it will give you something like this:



                  function updateUser (req, res) {
                  req.user.set(req.body);
                  req.user.save()
                  //... Then catch and handle validation error :)
                  }


                  More info on .set() method.

                  More info on model validation.







                  share|improve this answer








                  New contributor




                  laudeon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  share|improve this answer



                  share|improve this answer






                  New contributor




                  laudeon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  answered 10 hours ago









                  laudeonlaudeon

                  112




                  112




                  New contributor




                  laudeon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.





                  New contributor





                  laudeon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.






                  laudeon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.






















                      Catfish is a new contributor. Be nice, and check out our Code of Conduct.










                      draft saved

                      draft discarded


















                      Catfish is a new contributor. Be nice, and check out our Code of Conduct.













                      Catfish is a new contributor. Be nice, and check out our Code of Conduct.












                      Catfish is a new contributor. Be nice, and check out our Code of Conduct.
















                      Thanks for contributing an answer to Code Review Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      Use MathJax to format equations. MathJax reference.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214496%2fexpress-js-handler-to-update-user-fields%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Webac Holding Inhaltsverzeichnis Geschichte | Organisationsstruktur | Tochterfirmen |...

                      What's the meaning of a knight fighting a snail in medieval book illustrations?What is the meaning of a glove...

                      Salamanca Inhaltsverzeichnis Lage und Klima | Bevölkerungsentwicklung | Geschichte | Kultur und...