1 year ago

#262150

test-img

giovanni

GraphQL HTTP: "Cannot return null for non-nullable field Mutation.register."

I am trying to mutate in GraphQL to create a new user but I get the error of

Cannot return null for non-nullable field Mutation.register.

Screenshot of operation, variable and response here.

graphql/schema/schema.js

const{ buildSchema } = require('graphql');

const schema =  buildSchema(`

type User { 
  _id: ID!
  email: String!
  username: String!
  token: String!
  createdAt: String!
}
input RegisterInput{
  username: String!
  password: String!
  confirmPassword: String!
  email: String!
}
type Query { 
  user(id: ID!): User
}
type Mutation { 
  register(registerInput: RegisterInput): User!
}
schema { 
  query: Query
  mutation: Mutation
}
`)

module.exports = schema; 

graphql/resolvers/user.js

const User = require('../../models/user.js');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

const SECRET_KEY = 'oPXA96op!u%,`:}eT^.!|hvXohA~fa';

module.exports = {
    Mutation: {
        async register(
            _,
            {
                registerInput: { username, email, password, confirmPassword}
            },
            context,
            info
        ) {
            password = await bcrypt.hash(password, 12);

            const newUser = new User({
                email,
                username,
                password,
                createdAt: new Date().toISOString
            });

            const res = await newUser.save();

            const token = jwt.sign({
                id: res.id,
                email: res.email,
                username: res.username
            }, SECRET_KEY, { expiresIn: '1h'});

            return{
                ...res._doc,
                id: res._id,
                token
            };
        }
    }
};

graphql/resolvers/index.js

const postResolver = require('./post');
const userResolver = require('./user');

const resolvers = {
    Mutation: {
        ...userResolver.Mutation
    },
    ...postResolver
}

module.exports = resolvers;

server.js

const express = require('express'); 
const { ApolloServer, gql } = require('apollo-server-express');
const mongoose = require('mongoose');
const cors = require('cors');
const { graphqlHTTP } = require('express-graphql');

const MONGODB = ''; 

const schema = require('./graphql/schema');
const resolvers = require('./graphql/resolvers');
const PORT = 4000; 
   
const server = new ApolloServer({ schema, resolvers });

mongoose.connect(MONGODB); 
mongoose.connection.once('open', function() { 
  console.log('Connected to the Database.');
});
mongoose.connection.on('error', function(error) {
  console.log('Mongoose Connection Error : ' + error);
});

const app = express(); 
app.use(cors());

let apolloServer = null;
async function startServer() {
    apolloServer = new ApolloServer({
        schema,
        resolvers,
    });
    await apolloServer.start();
    apolloServer.applyMiddleware({ app });
}
startServer();

app.use("/graphql", graphqlHTTP({
  schema: schema,
  rootValue: resolvers, 
  graphiql: true
}));

app.listen(PORT, function() { 
  console.log(`Server listening on port ${PORT}.`);
});

I have checked many previous posts about this mutation error but none have seen to be resolved, and also have done many modifications to the schema/resolver but has not worked. I have also posted on the GraphQL Discord for help, but have had no luck. I tried changing the server.js but it affected my queries from running so I reverted.

/graphql/resolvers/post.js

const Post = require('../../models/post.js');
const { GraphQLDateTime } = require ('graphql-iso-date');

const customScalarResolver = {
    Date: GraphQLDateTime
  };
  
  function posts() { 
    return Post.find({});
  }
  
  function post(args) {
    return Post.findById(args.id)
  }
  
  function createPost(args) {
    let post = new Post(args.postInput);
    return post.save();
  }
  
  function deletePost(args) {
    return Post.findByIdAndRemove(args.id);
  }
  
  function updatePost(args) {
    return Post.findByIdAndUpdate(args.id, args.postInput, { new: true }); 
  }
  
  module.exports = { posts, post, createPost, deletePost, updatePost, customScalarResolver}

javascript

graphql

express-graphql

0 Answers

Your Answer

Accepted video resources