Apollo 无法在 class 的对象中上传文件

Apollo can't upload file in Object of class

在我的项目中,我尝试通过 Graphql 在多部分请求中上传文件。 问题是,当我创建一个包含文件的 class 的对象时,该文件没有上传。当它只是一个没有 class 的对象时,它正在工作。

这是有效的:

const upload = {
   file: new File()
};
apollo.mutate({
   mutation,
   variables:{
      fileParam: upload
   }
});

这不起作用:

class FileWrapper{
   constructor(public file: File){}
}
const upload = new FileWrapper(new File());
apollo.mutate({
   mutation,
   variables:{
      fileParam: upload
   }
});

这是有效的:

class FileWrapper{
   constructor(public file: File){}
}
const upload = new FileWrapper(new File());
apollo.mutate({
   mutation,
   variables:{
      fileParam: {...upload}
   }
});

我正在使用的软件包:

    "nuxt": "^2.0.0",
    "@nuxtjs/apollo": "^4.0.1-rc.1",

我用 createUploadLink 替换了标准的 HttpLink,如下所示:

  return ApolloLink.from([
    mutationTrackerLink(getModule(MutationTrackState, ctx.store), providerName),
    queueLink,
    serializingLink,
    retryLink,
    authLink,
    createUploadLink({
      uri: `${endpoint}/graphql`,
    }),
  ]);

我试图删除所有其他链接,但结果相同。

我将问题追溯到包裹:https://github.com/jaydenseric/extract-files 它检查是否 object.constructor === Object。当你有一个 class 的对象时,情况就不是这样了,因此它不会深入研究对象。

现在我用这个函数解决了这个问题,它使 class 的对象成为匿名对象。我主要从另一个 Whosebug post(不幸的是我忘记了哪个)复制了这个函数并稍微修改了它。

public static copyToAnonymusObject(obj: any) {
    let copy: any;

    // Handle the 3 simple types, and null or undefined
    if (obj === null || typeof obj !== 'object') return obj;

    // Handle File
    if (obj instanceof File) {
      return obj;
    }

    // Handle Date
    if (obj instanceof Date) {
      copy = new Date();
      copy.setTime(obj.getTime());
      return copy;
    }

    // Handle Array
    if (Array.isArray(obj)) {
      copy = [];
      for (let i = 0, len = obj.length; i < len; i++) {
        copy[i] = this.copyToAnonymusObject(obj[i]);
      }
      return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
      copy = {};
      Object.keys(obj).forEach((key) => {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          copy[key] = this.copyToAnonymusObject(obj[key]);
        }
      });
      return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
  }