I want to implement switch case for registration flow. Like normal sign up with
- email, Phone number and password
- with google
- 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:
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;
};
CodePudding user response:
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})
}
})