简体   繁体   English

Apollo Server 2.6 中的未知类型“上传”

[英]Unknown type "Upload" in Apollo Server 2.6

I want to upload a file through GraphQL, and followed this article .我想通过GraphQL上传一个文件,就跟着这篇文章

Here's the my schema:这是我的架构:

extend type Mutation {
  bannerAdd(
    title: String!
    image: Upload
  ): ID
}

However when I run the app, this gives me this error:但是,当我运行该应用程序时,这给了我这个错误:

Unknown type "Upload".未知类型“上传”。 Did you mean "Float"?您指的是 “Float” 吗?

Followed above article, Apollo Server will automatically generate Upload scalar, but why this is happening?按照上面的文章,Apollo Server会自动生成Upload scalar,但是为什么会这样呢?

Also define Upload scalar manually also not working:还手动定义上传标量也不起作用:

scalar Upload

...

Gives me this error:给我这个错误:

Error: There can be only one type named "Upload".错误:只能有一种名为“上传”的类型。

Seems nothing wrong with my code.我的代码似乎没有问题。 Is there an anything that I missed?有什么我错过的吗? Using Node@10.14.2, Apollo Server@2.6.1, Apollo Server Express@2.6.1 and polka@0.5.2.使用 Node@10.14.2、Apollo Server@2.6.1、Apollo Server Express@2.6.1 和 polka@0.5.2。

Any advice will very appreciate it.任何建议都会非常感激。

Fix this problem with GraphQLUpload of Apollo Server for create a custom scalar called FileUpload .使用 Apollo Server 的GraphQLUpload修复此问题,以创建名为FileUpload的自定义标量。

Server setup with Apollo Server:使用 Apollo Server 设置服务器:

const {ApolloServer, gql, GraphQLUpload} = require('apollo-server');

const typeDefs = gql`
  scalar FileUpload

  type File {
    filename: String!
    mimetype: String!
    encoding: String!
  }

  type Query {
    uploads: [File]
  }

  type Mutation {
    singleUpload(file: FileUpload!): File!
  }
`;

const resolvers = {
  FileUpload: GraphQLUpload,
  Query: {
    uploads: (parent, args) => {},
  },
  Mutation: {
    singleUpload: async (_, {file}) => {
      const {createReadStream, filename, mimetype, encoding} = await file;
      const stream = createReadStream();

      // Rest of your code: validate file, save in your DB and static storage

      return {filename, mimetype, encoding};
    },
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.listen().then(({url}) => {
  console.log(`🚀 Server ready at ${url}`);
});

Client Setup with Apollo Client and React.js:使用 Apollo Client 和 React.js 进行客户端设置:

You need to install the apollo-upload-client package too.您还需要安装apollo-upload-client包。

import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloClient, InMemoryCache, ApolloProvider, gql, useMutation } from '@apollo/client';
import { createUploadLink } from 'apollo-upload-client';

const httpLink = createUploadLink({
  uri: 'http://localhost:4000'
});

const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache()
});


const UPLOAD_FILE = gql`
  mutation uploadFile($file: FileUpload!) {
    singleUpload(file: $file) {
      filename
      mimetype
      encoding
    }
  }
`;

function FileInput() {
  const [uploadFile] = useMutation(UPLOAD_FILE);

  return (
    <input
      type="file"
      required
      onChange={({target: {validity, files: [file]}}) =>
        validity.valid && uploadFile({variables: {file}})
      }
    />
  );
}

function App() {
  return (
    <ApolloProvider client={client}>
      <div>
        <FileInput/>
      </div>
    </ApolloProvider>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App/>
  </React.StrictMode>,
  document.getElementById('root')
);

Here's the solution what I did, adding custom scalar named "FileUpload" and add GraphQLUpload as resolver like this:这是我所做的解决方案,添加名为“FileUpload”的自定义标量并添加 GraphQLUpload 作为解析器,如下所示:

import { GraphQLUpload } from 'graphql-upload';

export const resolvers = {
  FileUpload: GraphQLUpload
};

It works great, but it could be not perfect solution.它工作得很好,但它可能不是完美的解决方案。 Hope apollo fix this soon.希望阿波罗尽快解决这个问题。

PS To upload file from your browser, you also need to set upload link in Apollo Client properly. PS 要从浏览器上传文件,您还需要在 Apollo Client 中正确设置上传链接。 Here's my code:这是我的代码:

import { ApolloLink, split } from 'apollo-link';
import { createHttpLink } from 'apollo-link-http';
import { createUploadLink } from 'apollo-upload-client';

// Create HTTP Link
const httpLink = createHttpLink({
  uri: ...,
  credentials: 'include'
});

// Create File Upload Link
const isFile = value =>
  (typeof File !== 'undefined' && value instanceof File) || (typeof Blob !== 'undefined' && value instanceof Blob);
const isUpload = ({ variables }) => Object.values(variables).some(isFile);
const uploadLink = createUploadLink({
  uri: ...
  credentials: 'include'
});

const terminatingLink = (isUpload, uploadLink, httpLink);

const link = ApolloLink.from([<Some Other Link...>, <Another Other Link...>, terminatingLink]);

const apolloClient = new ApolloClient({
  link,
  ...
});

This issue can be caused by passing an executable schema ( schema option) when initializing your server instead of the newer API of passing typeDefs and resolvers separately.此问题可能是由于在初始化服务器时传递可执行模式( schema选项)而不是分别传递typeDefsresolvers的较新 API 引起的。

Old:老的:

const server = new ApolloServer({
    schema: makeExecutableSchema({ typeDefs, resolvers })
})

New:新的:

const server = new ApolloServer({
    typeDefs,
    resolvers,
})

Or as explained in the docs :或者如文档中所述:

Note: When using typeDefs, Apollo Server adds scalar Upload to your schema, so any existing declaration of scalar Upload in the type definitions should be removed.注意:使用 typeDefs 时,Apollo Server 会将scalar Upload添加到您的架构中,因此应删除类型定义中任何现有的标量上传声明。 If you create your schema with makeExecutableSchema and pass it to ApolloServer constructor using the schema param, make sure to include scalar Upload .如果您使用 makeExecutableSchema 创建架构并使用架构参数将其传递给 ApolloServer 构造函数,请确保包含scalar Upload

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未知类型“上传” - 带有 graphql-upload 节点 14 的 Apollo Server Express - Unknown type "Upload" - Apollo Server Express with graphql-upload Node 14 Apollo Server:弹出内置“上传”类型以使用 graphql-codegen 生成 TS 类型 - Apollo Server: Eject built in "Upload" Type to generate TS Types with graphql-codegen graphql apollo-server 中的文件上传错误 - File upload error in graphql apollo-server Docker 中的 Apollo 服务器上传文件失败 - Apollo Server Upload File failes in Docker 如何在NodeJS中使用GraphQL和Apollo Upload Server上传文件? - How to upload file with GraphQL and Apollo Upload Server in NodeJS? NodeJS - Apollo Server:在文件上传流解析期间请求断开连接 - NodeJS - Apollo Server: Request disconnected during file upload stream parsing 使用 graphql-upload 和 apollo-server 缺少多部分字段“操作” - Missing multipart field ‘operations’ with graphql-upload and apollo-server Apollo Server - GraphQL 错误:只能有一种名为“查询”的类型 - Apollo Server - GraphQL Error: There can be only one type named "Query" 带有Angular快速入门的Apollo:未知错误 - Apollo with Angular Quickstart : Unknown error 当我尝试使用 createReadStream 使用 apollo-server 上传文件时出现此错误, - I get this error when I try to upload a file with apollo-server using createReadStream ,
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM