未提供所需类型 "Upload!" 的变量“$picture”

Variable "$picture" of required type "Upload!" was not provided

我正在尝试使用 apollo-upload-client 从 Next.js 应用程序使用 graphql 将文件上传到 Node.js 后端。

我的 Apollo 客户端配置

const createClient = (ctx: NextPageContext) =>
new ApolloClient({
  credentials: "include",
  headers: {
    cookie:
      (typeof window === "undefined"
        ? ctx?.req?.headers.cookie
        : undefined) || "",
  },
  cache: new InMemoryCache(),
  link: createUploadLink({uri:'http://localhost:4000/graphql', credentials:"include"})
});

我的带有 TypeORM 的快速解析器

@Resolver()
export class ProfilePictureResolver {
  @Mutation(() => Boolean)
  async addProfilePicture(@Arg("picture", () => GraphQLUpload)
  {
    createReadStream,
    filename
  }: Upload): Promise<boolean> {
    return new Promise(async (resolve, reject) =>
      createReadStream()
        .pipe(createWriteStream(__dirname + `/../../../images/${filename}`))
        .on("finish", () => resolve(true))
        .on("error", () => reject(false))
    );
  }
}

页数

const Profile:React.FC<IProps> = () => {

  const user = useSelector(state => state.user);
  const [file, setFileToUpload] = useState(null);
  const [mutate, {loading}] = useMutation(UPLOAD_IMAGE_MUTATION);


   function onChange({
    target: {
      validity,
      files: [file],
    },
  }) {
    if (validity.valid) mutate({ variables: { picture: file } });
  }

  const onSubmit = async (e) =>{
    e.preventDefault();
    console.log(file)
    const response = await mutate({
          variables: {picture: file}
    });


  }

    return (
        <Box mt={20} pl={30} pr={30}>
          <Header>
            Edit Profile
          </Header>
          <input onChange={onChange} type="file" placeholder="photo" />
          <button onClick={(e)=>onSubmit(e)}>Submit</button>
        </Box>
      
    )
};

表格数据

------WebKitFormBoundary3bcoEmOQWM0eUhCG Content-Disposition: form-data; name="operations"

{"operationName":"addProfilePicture","variables":{"picture":null},"query":"mutation addProfilePicture($picture: Upload!) {\n addProfilePicture(picture: $picture)\n}\n"} ------WebKitFormBoundary3bcoEmOQWM0eUhCG Content-Disposition: form-data; name="map"

{"1":["variables.picture"]} ------WebKitFormBoundary3bcoEmOQWM0eUhCG Content-Disposition: form-data; name="1"; filename="73387406_149357266327075_4919835380817576193_n.jpg" Content-Type: image/jpeg

------WebKitFormBoundary3bcoEmOQWM0eUhCG--

在控制台中调用突变之前,我看到该文件存在。我做错了什么?

更新: 我在客户端修复了突变,在 picture:file 上更改了 file。 现在我有另一个错误:

Variable "$picture" got invalid value {}; Upload value invalid.

更新二:

这是我的查询,可能会有帮助

js export const UPLOAD_IMAGE_MUTATION = gql` mutation addProfilePicture($picture: Upload!) { addProfilePicture(picture: $picture) } `;

解决方案

我发现我的 apollo 服务器解析器确实有问题

我已经在这个上更改了旧的解析器(见上文):

 uploadFile: async (_, { file }) => {
      const { createReadStream, filename } = await file;

      await new Promise(res =>
        createReadStream()
          .pipe(createWriteStream(path.join(__dirname, "../images", filename)))
          .on("close", res)
      );

      files.push(filename);

      return true;
    },

如你所见,我不再使用 graphql 上传,而且我已将我的客户端突变改回

mutate({ variables: { file } }

以及新的突变查询:

  mutation UploadFile($file: Upload!) {
    uploadFile(file: $file)
  }

现在它就像一个魅力。结案。

如错误所示,您的操作包含一个名为 $picture 的变量,但您没有提供这样的变量。调用 mutate 时,您提供的唯一变量是一个名为 $file 的变量。你应该改为:

const response = await mutate({
  variables: { picture: file },
});

我发现我的 apollo 服务器解析器确实有问题

我已经从这个问题的问题中更改了旧的解析器:

 uploadFile: async (_, { file }) => {
      const { createReadStream, filename } = await file;

      await new Promise(res =>
        createReadStream()
          .pipe(createWriteStream(path.join(__dirname, "../images", filename)))
          .on("close", res)
      );

      files.push(filename);

      return true;
    },

如你所见,我不再使用 graphql 上传,而且我已将我的客户端变更改回

mutate({ variables: { file } }

以及新的突变查询:

  mutation UploadFile($file: Upload!) {
    uploadFile(file: $file)
  }

现在它就像一个魅力。