阿波罗无法在类

时间:2020-06-25 08:43:28

标签: typescript nuxt.js apollo vue-apollo

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

这有效:

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`,
    }),
  ]);

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

1 个答案:

答案 0 :(得分:0)

我将问题追溯到软件包:https://github.com/jaydenseric/extract-files 它检查是否object.constructor === Object。当您拥有类的对象时,情况并非如此,因此它不会深入到该对象中。

现在,我使用此函数解决了该问题,该函数使类的对象成为匿名对象。我主要从另一篇StackOverflow帖子中复制了此函数(不幸的是,我忘记了哪一篇),并对其进行了一些修改。

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.");
  }