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

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

我没有得到任何通过 GraphQL、Apollo Server 在 NodeJS 中上传文件的正确示例。

我已经编写了一个 mutation 来发送完美运行的消息。下面是代码 sendMessage.js 变异

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

现在,我想在同一变更中添加上传文件功能。请帮助我该怎么做。

提前致谢。

我相信您会在 apollo-universal-starter-kit 项目中找到所有需要的部分(客户端+服务器)。

这里是 client/server 演示:https://github.com/mrdulin/react-apollo-graphql

这是服务器演示:https://github.com/mrdulin/apollo-server-express-starter/tree/master/src/fileupload