如何在NodeJS中使用GraphQL和Apollo Upload Server上传文件?

问题描述 投票:3回答:2

我没有得到任何适当的例子来通过GraphQL,NodeJS中的Apollo Server上传文件。

我写了一个突变来发送完全有效的消息。这是代码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);
  }
}
);

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

提前致谢。

node.js graphql apollo-server
2个回答

1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.