当前,我正在通过Google建立登录功能,但有些问题使我有些困惑。
我们可以在一个项目中同时使用Restful API和Graphql API吗?除了Google身份验证之外,我们还需要一些方法来进行处理。对于CRUD操作,我们使用Graphql。
类似这样的东西:
const { GraphQLServer } = require('graphql-yoga');
const { Prisma } = require('prisma-binding');
const resolvers = require('./resolvers');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
// mongoose.
User.findById(id).then(user => {
done(null, user);
});
});
passport.use(new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback',
},
(accessToken, refreshToken, profile, done) => {
console.log(profile);
// After receive profile info from google, call mutation and save
// profile into database.
}
));
const db = new Prisma({
typeDefs: 'src/generated/prisma.graphql',
endpoint: process.env.PRISMA_ENDPOINT,
debug: true,
secret: process.env.PRISMA_SECRET,
});
const server = new GraphQLServer({
typeDefs: './src/schema.graphql',
resolvers,
resolverValidationOptions: {
requireResolversForResolveType: false
},
context: req => ({ ...req, db })
});
server.express.get('/auth/connect', passport.authenticate('google', {
scope: ['profile', 'email']
}));
server.express.get('/auth/google/callback', passport.authenticate('google'));
server.start(() => console.log(`Server is running on ${process.env.PRISMA_ENDPOINT}`));
在GoogleStrategy
的回调函数中,如何调用Mutation并将所有个人资料信息从Google保存到数据库?
(accessToken, refreshToken, profile, done) => {
console.log(profile);
// After receiving profile info from google, call mutation and save
// profile into the database.
}
在deserializeUser
和serializeUser
函数中。以前,当我使用Nodejs和MongoDB时,我已经做到了:
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
// mongoose.
User.findById(id).then(user => {
done(null, user);
});
});
对于Prisma和Graphql,该如何解决突变问题?
答案 0 :(得分:0)
在服务器中,创建prisma-binding
实例,然后将其传递到graphql-yoga
的上下文。这样,您就可以像这样在旋转变压器中进行棱镜操作:
context.db.query.user({where: {id: 'ABCD'}})
但这并不意味着您不能在其他地方使用prisma-binding
实例!
在护照回调中,您也可以访问prisma-binding
实例并调用查询和变异:
db.mutation.createUser({data: {name: 'John Doe'}})