5

I did not get any proper example to upload a file via GraphQL, Apollo Server in NodeJS.

I have written a mutation to send the message that is perfectly working. Here is the code sendMessage.js Mutation

const sendMessage = {
    type: ChatType,
    args: {
        input: {
            type: new GraphQLNonNull(new GraphQLInputObjectType({
                name: 'ChatMessageInput',
                fields: {
                    toUserId:{
                        name:'To User ID',
                        type: new GraphQLNonNull(GraphQLID)
                    },
                    message:{
                        name:'Message',
                        type: new GraphQLNonNull(GraphQLString)
                    }
                }
            }))
        },
        file:{
            name: "File",
            type: uploadType
        }
    },
    async resolve(_, input, context) {

    }
    };

module.exports = sendMessage;

Here the code I have written for creating the GraphQl End Point.

app.use('/api', bodyParser.json(), jwtCheck, 
apolloUploadExpress({ uploadDir: "./uploads",maxFileSize: 10000000, maxFiles: 10 }),
graphqlExpress(req => ({
  schema,
  context: {
    user: req.user,
    header:req.headers
  },
  formatError: error => ({
    status:error.message[0].status,
    message: error.message[0].message,
    state: error.message
  })
})),function (err, req, res, next) {
  if (err.name === 'UnauthorizedError') { // Send the error rather than to show it on the console
    //console.log(err);
      res.status(401).send({errors:[err]});
  }
  else {
      next(err);
  }
}
);

Now, I want to add upload file functionality in the same mutation. Please help me how can I do that.

Thanks in advance.

2 Answers 2

2

Here is client/server demo: https://github.com/mrdulin/react-apollo-graphql

Here is server demo: https://github.com/mrdulin/apollo-server-express-starter/tree/master/src/fileupload

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. You defined the upload model in gql language. I did not know how to define an interface in node js without gql. The way I wrote mutation definition code (in the given question), could you please guide me how can I do that in that same way.. Please help me regarding this. Thanks
1

I'm sure you'll find all needed parts (client+server) in apollo-universal-starter-kit project.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.