Piyush Bansal
Piyush Bansal

Reputation: 1723

How to upload file with GraphQL and Apollo Upload Server in NodeJS?

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.

Upvotes: 4

Views: 8589

Answers (2)

xadm
xadm

Reputation: 8418

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

Upvotes: 1

Related Questions