17

文件上传似乎是一种突变。它通常伴随着其他数据。但它是一个很大的二进制 blob,所以我不确定 GraphQL 如何处理它。您如何将文件上传集成到使用 Relay 构建的应用程序中?

4

5 回答 5

10

首先,您需要在前端组件中编写中继更新。像这样:

onDrop: function(files) {
  files.forEach((file)=> {
    Relay.Store.commitUpdate(
      new AddImageMutation({
        file,
        images: this.props.User,
      }),
      {onSuccess, onFailure}
    );
  });
},

然后在前端实现突变:

class AddImageMutation extends Relay.Mutation {
   static fragments = {
     images: () => Relay.QL`
       fragment on User {
         id,
       }`,
     };

   getMutation() {
     return Relay.QL`mutation{ introduceImage }`;
   }

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

   getVariables() {
     return {
       imageName: this.props.file.name,
     };
   }

   getFatQuery() {
     return Relay.QL`
       fragment on IntroduceImagePayload {
         User {
           images(first: 30) {
             edges {
               node {
                 id,
               }
             }
           }
         },
         newImageEdge,
       }
     `;
   }

   getConfigs() {
     return [{
       type: 'RANGE_ADD',
       parentName: 'User',
       parentID: this.props.images.id,
       connectionName: 'images',
       edgeName: 'newImageEdge',
       rangeBehaviors: {
         '': 'prepend',
       },
     }];
   }
 }

最后,在服务器/模式上实现处理程序。

const imageMutation = Relay.mutationWithClientMutationId({
  name: 'IntroduceImage',
  inputFields: {
    imageName: {
      type: new GraphQL.GraphQLNonNull(GraphQL.GraphQLString),
    },
  },
  outputFields: {
    newImageEdge: {
      type: ImageEdge,
      resolve: (payload, args, options) => {
        const file = options.rootValue.request.file;
        //write the image to you disk
        return uploadFile(file.buffer, filePath, filename)
        .then(() => {
          /* Find the offset for new edge*/
          return Promise.all(
            [(new myImages()).getAll(),
              (new myImages()).getById(payload.insertId)])
          .spread((allImages, newImage) => {
            const newImageStr = JSON.stringify(newImage);
            /* If edge is in list return index */
            const offset = allImages.reduce((pre, ele, idx) => {
              if (JSON.stringify(ele) === newImageStr) {
                return idx;
              }
              return pre;
            }, -1);

            return {
              cursor: offset !== -1 ? Relay.offsetToCursor(offset) : null,
              node: newImage,
            };
          });
        });
      },
    },
    User: {
      type: UserType,
      resolve: () => (new myImages()).getAll(),
    },
  },
  mutateAndGetPayload: (input) => {
    //break the names to array.
    let imageName = input.imageName.substring(0, input.imageName.lastIndexOf('.'));
    const mimeType = input.imageName.substring(input.imageName.lastIndexOf('.'));
    //wirte the image to database
    return (new myImages())
    .add(imageName)
    .then(id => {
    //prepare to wirte disk
      return {
        insertId: id,
        imgNmae: imageName,
      };
    });
  },
});

上面的所有代码你都可以在我的 repo 中找到它们https://github.com/bfwg/relay-gallery 还有一个现场演示https://fanjin.io

于 2016-02-23T18:36:27.010 回答
5

在文档中找到了解释。您可以继承 Relay.Mutation 并实现 getFiles 函数。

此外,express-graphql 在其测试用例中提供了一个示例,说明如何在服务器端处理此问题。

于 2015-10-11T11:00:39.487 回答
4

我只是在他的博客中分享 Marc-Andre Giroux 的发现,这是特定于 Rails 的,所以我将尝试使其更通用,并提供@Nick 提供的答案的详细信息。

有2个部分:

  • 客户端 Javascript 代码
  • 服务器端特定于服务器的代码

客户端 Javascript 代码

客户端代码进一步由两部分组成:

  1. 上传文件的突变,它扩展了 Relay.Mutation (UploadFileMutation)

    // The actual mutation
    class UploadFileMutation extends Relay.Mutation {
      getFiles() {
        return {
          file: this.props.file,
        };
      }
    
      // ... Rest of your mutation
    }
    
  2. 包含 React 组件 (FileUploader) 的组件,用于呈现用于选择文件的 UI,并调用突变进行上传

    // A react component to upload a file
    class FileUploader extends React.Component {
      onSubmit() {
        const name = this.refs.name.value;
        const file = this.refs.fileInput.files.item(0);
        Relay.Store.update(
          new UploadFileMutation({
            name: name,
            file: file,
          })
        );
      }
    
      // ... Rest of React component, e.g., render()
    }
    

服务器端服务器特定代码

服务器端代码也由两部分组成:

  1. 处理以 MIME 多部分格式检索上传文件并将其传递给 GraphQL 模式中定义的 Mutation 的部分。我们提供了 NodeJS 和 Rails 示例,它们应该可以帮助您为其他服务器派生解决方案。

对于 NodeJS Express 服务器(从@Nick指出的express-graqphl测试用例中提取):

    import multer from 'multer';

    var app = express();
    var graphqlHTTP = require('express-graphql');

    // Multer provides multipart form data parsing.
    var storage = multer.memoryStorage();

    app.use(urlString(), multer({ storage }).single('file'));

    // Providing the request, which contains the file MIME
    // multipart as `rootValue` to enable it to
    // be accessible from within Schema resolve functions.
    app.use(urlString(), graphqlHTTP(req => {
      return {
        schema: YourMutationSchema,
        rootValue: { request: req }
      };
    }));

同样,对于非 JS 服务器,例如 RubyOnRails:

    def create
      query_string = params[:query]
      query_variables = ensure_hash(params[:variables]) || {}

      query = GraphQL::Query.new(
        YourSchema,
        query_string,
        variables: query_variables,
        # Shove the file MIME multipart into context to make it
        # accessible by GraphQL Schema Mutation resolve methods
        context: { file: request.params[:file] }
     )
  1. Mutation 可以检索传递给它的文件 MIME multipart

对于 Javascript GraphQL 架构:

    var YourMutationSchema = new GraphQLSchema({
      query: new GraphQLObjectType({
        // ... QueryType Schema
      }),
      mutation: new GraphQLObjectType({
        name: 'MutationRoot',
        fields: {
          uploadFile: {
            type: UploadedFileType,
            resolve(rootValue) {
              // Access file MIME multipart using
              const _file = rootValue.request.file;

              // ... Do something with file
            }
          }
        }
      })
    });

对于 Rails GraphQL 模式:

    AddFileMutation = GraphQL::Relay::Mutation.define do
      name "AddFile"
      input_field :name, !types.String

      # ... Add your standard mutation schema stuff here

      resolve -> (args, ctx) {
        # Retrieve the file MIME multipart
        file = ctx[:file]
        raise StandardError.new("Expected a file") unless file

        # ... Do something with file
      }
    end
于 2016-03-13T10:20:57.623 回答
1

为了添加其他答案,对于 Relay Modern,您应该如何从客户端发送文件有一个小的变化。getFiles您可以使用以下内容,而不是在您的突变中使用 a 并将文件传递给构造函数:

上传文件突变.js

// @flow

import { commitMutation, graphql } from 'react-relay';

import type { Environment } from 'react-relay';
import type { UploadFileInput, UploadFileMutationResponse } from './__generated__/uploadFileMutation.graphql';

const mutation = graphql`
  mutation UploadFileMutation( $input: UploadFileInput! ) {
    UploadFile(input: $input) {
      error
      file {
        url
      }
    }
  }
`;

const getOptimisticResponse = (file: File | Blob) => ({
  UploadFile: {
    error: null,
    file: {
      url: file.uri,
    },
  },
});

function commit(
  environment: Environment,
  { fileName }: UploadFileInput,
  onCompleted: (data: UploadFileMutationResponse) => void,
  onError: () => void,
  uploadables,
) {
  return commitMutation(environment, {
    mutation,
    variables: {
      input: { fileName },
    },
    optimisticResponse: getOptimisticResponse(uploadables.fileToUpload),
    onCompleted,
    onError,
    uploadables,
  });
}

export default { commit };

组件上的用法:

const uploadables = {
  fileToUpload: file, // file is the value of an input field for example
};

UploadFileMutation.commit(
  this.props.relay.environment,
  { fileName },
  onCompleted,
  onError,
  uploadables
);

配置uploadables选项有点隐藏,因为文档中没有提到它,但可以在这里找到:https ://github.com/facebook/relay/blob/c4430643002ec409d815366b0721ba88ed3a855a/packages/relay-runtime/mutations/ commitRelayModernMutation.js#L32

于 2017-07-26T15:00:26.507 回答
1

虽然您绝对可以实现将文件上传到 GraphQL API 端点,但它被认为是一种反模式(您会遇到最大文件大小等问题)。

更好的选择是从您的 GraphQL API 获取签名 URL,以便将文件直接从客户端应用程序上传到 Amazon S3、Google Cloud Storage 等。

如果服务器端代码需要在上传完成后将 URL 保存到数据库中,可以直接订阅该事件。以 Google Cloud中的对象更改通知为例。

mutation {
  getUploadURL(filename: "example.jpg")
}

您可以在GraphQL API & Relay Starter Kit中找到示例→api/mutations/getUploadURL.ts

于 2019-09-05T08:50:30.867 回答