I wrote 2 resolvers (signup and login). They return a JWToken. In playground, I'm testing the functions and it won't let me make a mutation without specifying some subfields to display. They all are null and sometimes I get a "Cannot return null for non-nullable field users._id". I'm using express and mongodb.
const { UserTC, UserSchema } = require("../models/user");
const bcrypt = require('bcrypt')
const jsonwebtoken = require('jsonwebtoken')
const resolver = function () {};
resolver.me = UserTC.addResolver({
name: "me",
type: UserTC,
args: { record: UserTC.getInputType() },
resolve: async ({ source, args }) => {
if (!args.record) {
throw new Error('You are not authenticated!')
}
return await UserSchema.findById(args.record._id)
}
});
resolver.signup = UserTC.addResolver({
name: "signup",
type: UserTC,
args: { record: UserTC.getInputType() },
resolve: async ({ source, args }) => {
const user = await UserSchema.create({
firstName: args.record.firstName,
lastName: args.record.lastName,
email: args.record.email,
password: await bcrypt.hash(args.record.password, 10)
});
return jsonwebtoken.sign(
{ id: user._id, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: '1y' }
)
},
});
resolver.login = UserTC.addResolver({
name: "login",
type: UserTC,
args: { record: UserTC.getInputType() },
resolve: async ({ source, args }) => {
const user = await UserSchema.findOne({email: args.record.email });
if (!user) {
throw new Error('Incorrect email')
}
const valid = await bcrypt.compare(args.record.password, user.password);
if (!valid) {
throw new Error('Incorrect password')
}
return jsonwebtoken.sign(
{ id: user._id, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: '1y' }
)
},
});
module.exports = resolver;
Here are the queries:
mutation {
signup(
record: {
firstName: "Ben2"
lastName: "Dormant"
email: "[email protected]"
password: "qwerty"
}
)
}
mutation {
login(record: {
email: "[email protected]",
password: "azerty" })
}
question from:
https://stackoverflow.com/questions/65859527/how-do-i-retrieve-what-i-return-graphql-query-newbie 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…