Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested handlers #92

Open
Jbarget opened this issue Dec 8, 2017 · 0 comments
Open

Nested handlers #92

Jbarget opened this issue Dec 8, 2017 · 0 comments

Comments

@Jbarget
Copy link

Jbarget commented Dec 8, 2017

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);
         }
      });
   }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant