簡體   English   中英

在 node.js 中使用開關盒

[英]Use switch case in node.js

我想為注冊流程實現切換案例。 像正常注冊一樣

  1. email,電話號碼和密碼
  2. 與谷歌
  3. 與 facebook 等。

如果用戶選擇繼續使用谷歌按鈕然后切換到谷歌注冊等等。 我怎樣才能做到這一點?

controller 文件:

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

用戶服務文件:

// 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;
};

我建議使用解構 object。 不建議使用開關,這對 memory 和性能不利

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})
 }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM