在使用apollo-client v2和rails(graphql-ruby)的情况下,创建文件上传mutation的方法是什么?
请说明问题。
-
- apollo-client v2目前还不能处理上传文件的mutation?看起来是这样的。
通过使用https://github.com/jaydenseric/apollo-upload-client,可以创建能够上传文件的mutation。
然而,由于文件上传的场景与服务器(本次是rails + graphql-ruby)预期的params内容不一致,因此无法直接接收文件。
# fileをアップロードしない場合のキー
# app/controllers/graphql_controller.rb
def execute
params.keys
=> ["query",
"variables",
"controller",
"action",
"graphql"]
# fileをアップロード**する**場合のキー
# app/controllers/graphql_controller.rb
def execute
params.keys
=> ["operations",
"map",
"0",
"controller",
"action"]
解决方案
考虑到嵌套状态等复杂情况,因此将其转化为gem形式,以简化操作。
https://github.com/github0013/graphql_apollo_upload_client_params
class GraphqlController < ApplicationController
def execute
# paramsを使いやすいように加工する
converted_params = GraphqlApolloUploadClientParams.convert(params)
variables = converted_params.variables
query = converted_params.query
operation_name = converted_params.operation_name
然后从客户端按照正常方式调用mutation。
-
- 变量直接下
-
- 作为嵌套对象的属性
-
- 作为数组
- 保持为FileList
传递要上传的文件对象
mutation($file: File!) {
testField(file: $file)
}
...
...
this.props
.mutate({
variables: {
file: fileObject
}
})
.then(({ data }) => {
console.log(data)
})
为了接收文件,需要在服务器端将相应的mutation参数类型设置为自定义的File标量类型。
FileType = GraphQL::ScalarType.define do
name "File"
description "ActionDispatch::Http::UploadedFile"
coerce_input ->(action_dispatch_uploaded_file, ctx) {
action_dispatch_uploaded_file
}
end
其他方面都可以像通常一样使用文件作为参数进行参考。