
Using GraphQL Code Generator (TypeScript) with Apollo
Let’s say you have a GraphQL API and now you want to start accepting file uploads. This is possible using the following the Upload
Scalar type from graphql-upload
, as detailed here https://www.apollographql.com/docs/apollo-server/data/file-uploads/ (keep in mind you will need to use the graphql-multipart-request-spec
to actually upload files, as explained here https://github.com/jaydenseric/graphql-multipart-request-spec)
However, when using GraphQL Code Generator with TypeScript you might run into an issue with the Upload
scalar type as this is not a default GraphQL scalar type. To fix this we will need to add 2 things:
1. Update the schema to accept the scalar Type
First off we need to tell the schema the scalar type actually exists. We can do this by simply adding scalar Upload
to the top of the schema file.
2. Update the codegen configuration
Now we need to update our configuration so it will use the correct typing for the newly defined scalar type. We can do this by using the scalars
configuration key. (as can be found here https://graphql-code-generator.com/docs/plugins/typescript)
The simplest way to configure this is as follows:
config:
scalars:
Upload: import('graphql-upload').FileUpload
All set! Now the resulting code generation will have something like this:
export type Scalars = {
...
Upload: import('graphql-upload').FileUpload;
};
This will way you can make your custom file upload resolvers completely type safe!