Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use switch case in node.js

I want to implement switch case for registration flow. Like normal sign up with

  1. email, Phone number and password
  2. with google
  3. with facebook etc.

If user selects the continue with google button then switch to google registration and so on. How can I do that?

The controller file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

exports.register = catchAsync(async (req, res, error) => {
  try {
    const user = await userService.googleRegistration(req);
  } catch (error) {
    return res.failed(500, "Internal server error", error);
  }
});

The userService file:

// GOOGLE REGISTRATION
exports.googleRegistration = async (req) => {
  var google = require("googleapis").google;
  var OAuth2 = google.auth.OAuth2;
  var oauth2Client = new OAuth2();
  oauth2Client.setCredentials({ access_token: req.params.access_token });
  var oauth2 = google.oauth2({
    auth: oauth2Client,
    version: "v2",
  });
  oauth2.userinfo.get(async (err, res) => {
    if (err) {
    } else {
      let user_data = new User({
        first_name: res.data.given_name,
        last_name: res.data.family_name,
      });
      let user = await user_data.save();
      return user;
    }
  });
};

// NORMAL REGISTRATION
exports.register = async (user) => {
  let new_user = new User({ ...user });
  const user_data = await new_user.save();

  const payload = { id: new_user._id };
  user_data.JWToken = jwt.sign(payload, keys.JWToken, { expiresIn: 31556926 });

  return user_data;
};

>Solution :

I recomended use an des-structuct object. NOT recomended use a switch it is bad for the memory and performance

const typeSingIn = {
 facebook: function(){ /* function to join with fb */},
 google: function() {/* your function to join with google*/},
 // more options
}

app.post("/singIn", (req, res) => {
 const {method} = req.body // expect the answer if the signIn is for fb, google or other method.
 const singInType = typeSignIn[method]
 try{
  signInType() // this can be a promise if you want it
 }catch(e){
  res.json({status: 500, message: e})
 }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading