简体   繁体   中英

Apollo Server: Eject built in "Upload" Type to generate TS Types with graphql-codegen

I am using graphql-codegen to generate my TS Types of my GraphQL TypeDef files. I also use the built in Upload Type from apollo server to handle file uploads but the Upload TypeDef is not in my own schema, its somewhere built into apollo-server itself. When I try to generate via the graphql-codegen , I receive an error:

Error: Unknown type "Upload". Did you mean "Float"?

Unknown type "Upload". Did you mean "Float"?

because its not in my own typedef files.

Can I somehow eject the builtin apollo "Upload" type to add the typedef by myself?

I was facing the same issue. You have to define your own Upload type, define a custom scalar in your codegen.yml config file, and some other things.

# codegen.yml
config:
  scalars:
    Date: Date
    Upload: FileUpload

You can import your custom FileUpload type in your generated files with the plugin add-content of graphql-codegen ( @graphql-codegen/add ):

# codegen.yml
generates:
  # Schema ans resolvers types
  ./src/graphql/generated/schema.types.ts:
    plugins:
      - add:
          content: "import { FileUpload } from \"path/to/your/type/file\""
      - typescript
import { ReadStream } from "fs"

export interface FileUpload {
  filename: string
  mimetype: string
  encoding: string
  createReadStream(): ReadStream
}

BTW, you should install @types/node . And, in order to make things simpler, you must define a scalar in your graphql schema (otherwise graphl-cogeden will tell you that Upload is unknown.

So:

# schema.graphql
scalar Upload

And, if you use Apollo Server 2, the default Apollo's behaviour is to automatically add scalar Upload in your schema, so you need to use the makeExecutableSchema from, graphql-tools !

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

Enjoy!

ok if you have this error just "import" the scalar (its not a type)

via

scalar Upload

in your typedef

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM