I want to refactor this code so I can put the whole DB query logic in a different file and just call only the function in this file, how would I go about that?
passport.use(
new GoogleStrategy({
clientID: googleId,
clientSecret: clientSecret,
callbackURL: 'http://localhost:5000/auth/google/callback',
}, (accessToken, refreshToken, profile, done)=> {
User.findOne({googleid:profile.id}).then((currentUser)=>{
if(currentUser){
console.log(`current User: ${currentUser}`)
done(null,currentUser)
}else{
new User ({
name:profile.displayName,
googleid:profile.id
}).save().then((user) => {console.log(`newly created user: ${user}`); done(null, user)})
}
})
})
)
CodePudding user response:
You can put the database code in a separate module where you export a function to use in the strategy and then this strategy file can import that function and use it here in the GoogleStrategy
implementation.
This is how modules are used in nodejs to organize code.
Here's one way you could separate out the code:
import { processUser } from "./db-helper.js";
passport.use(
new GoogleStrategy({
clientID: googleId,
clientSecret: clientSecret,
callbackURL: 'http://localhost:5000/auth/google/callback',
}, (accessToken, refreshToken, profile, done) => {
processUser(profile).then(user => {
done(null, user);
}).catch(done);
});
);
And, then in db-helper.js
export async function processUser(profile) {
const currentUser = await User.findOne({ googleid: profile.id });
if (currentUser) {
console.log(`current User: ${currentUser}`)
return currentUser;
} else {
const user = await new User({
name: profile.displayName,
googleid: profile.id
}).save();
console.log(`newly created user: ${user}`);
return user;
}
}