Skip to content

Nested handlers #92

@Jbarget

Description

@Jbarget

https://github.com/fac-12/BudgetPlanner/blob/master/src/handler.js#L91-L126

Typically this is a prime use case for promises (but know that you only dabbled with that a little this week). This is a bit tricky, and hard to test, what you'll want to do here is create new functions that you pass in as arguments instead of nesting.

eg.

const createUserHandler = (err, res) => {
    if (err) {
       response.writeHead(500, { 'content-type': 'text/html' });
       response.end('Oops! There was a problem');
   } else {
      let userIdName = JSON.parse(res);
      const cookie = sign(userIdName, process.env.SECRET);
      response.writeHead(302, { 'Location': '/main', 'Set-Cookie': `jwt=${cookie}; HttpOnly` });
      response.end('You have succesfully signed in');
   }
}

if (validateUser(userData) === true) {
   checkUser(userData, (err, res) => {
      if (err) {
         response.writeHead(500, { 'content-type': 'text/html' });
         response.end('Oops! There was a problem');
      } else if (res === 1) {
         response.writeHead(401, { 'content-type': 'text/html' })
         response.end(`Username: ${userData.username} already exists, try logging in`);
     } else if (res === 0) {
         genHashedPassword(userData, (err, result) => {
          if (err) {
            response.writeHead(500, { 'content-type': 'text/html' });
            response.end('Oops! There was a problem');
         } else {
             createUser(result, createUserHandler);
         }
      });
   }
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions