如何在NodeJS中使用GraphQL和Apollo上传服务器上传文件?

4

我没有找到任何合适的例子来通过GraphQL、Apollo Server在NodeJS中上传文件。

我已经编写了一个可以成功发送消息的mutation。下面是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;

这里是我编写用于创建GraphQl端点的代码。

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);
  }
}
);

现在,我想在同一个mutation中添加上传文件的功能。请帮忙告诉我如何实现。
提前感谢。
2个回答

2

谢谢你的回答。你用gql语言定义了上传模型。我不知道如何在node js中定义接口而不使用gql。我写的mutation定义代码(在给定的问题中),你能否指导我如何以同样的方式做到这一点。请帮助我解决这个问题。谢谢。 - Piyush Bansal

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接