如何使用 Relay Modern 突变进行文件上传?

How to do file uploads with Relay Modern mutations?

我正在使用 react-relay/compat 1.1.0,我需要编写一个能够上传文件的 mutation。 在 Relay Classic 中,您可以使用 getFiles() 来支持突变中的文件上传:

class AddImageMutation extends Relay.Mutation {
   getMutation() {
     return Relay.QL`mutation{ introduceImage }`;
   }

   getFiles() {
     return {
       file: this.props.file,
     };
   }
   ...
}

但是在 Relay Modern 文档中没有找到任何上传文件功能的踪迹:

const {commitMutation} = require('react-relay');

commitMutation(
  environment: Environment,
  config: {
    mutation: GraphQLTaggedNode,
    variables: Variables,
    onCompleted?: ?(response: ?Object) => void,
    onError?: ?(error: Error) => void,
    optimisticResponse?: ?() => Object,
    optimisticUpdater?: ?(store: RecordSourceSelectorProxy) => void,
    updater?: ?(store: RecordSourceSelectorProxy) => void,
    configs?: Array<RelayMutationConfig>,

    // files: ... ?
  },
);

relay modern 支持吗?如果是这样,这样做的方法是什么?谢谢。

发现了这个问题,因为我自己也有同样的问题。

还不确定完整的答案,但我开始通读中继源并基于 packages/relay-runtime/mutations/commitRelayModernMutation.js 看起来你可以将 uploadables 传递给你的突变。

您必须在 commitMutationconfig 对象中将文件作为对象 uploadables 提供,然后在您的网络层实现实际上传,因为对服务器的提取请求必须是多部分形式,而不是 application/json.

有关完整示例,请参阅 https://github.com/facebook/relay/issues/1844#issuecomment-316893590