NestJS file upload with GraphQL

Dilusha Dasanayaka
2 min readMay 24, 2021

--

Bonjour machan!😜 Today let’s create a GraphQL endpoint to upload files in NestJS. You should have a basic idea about GraphQL and NestJS to get the most out of this article.

First, let’s create a nestJS and I’m going to name it graphql-fileupload.

nest new graphql-fileupload

Then install the following dependencies. Here we going to use graphql-upload package additionally to handle the file upload.

npm i @nestjs/graphql graphql-tools graphql apollo-server-express graphql-upload

Then import the GraphQL module & configure it with forRoot() in app.module.ts file. Make sure to disable the uploads. Will discuss the reason later 😉.

@Module({
imports: [
GraphQLModule.forRoot({
autoSchemaFile: 'schema.gql',
uploads: false,
}),
],
})

In the resolver file, we let’s create a mutation to handle the file upload.

@Mutation(() => Boolean)
async uploadFile(
@Args({name: 'file', type: () => GraphQLUpload)
{createReadStream,filename}: FileUpload
){
/** now you have the file as a stream **/}

Now we are all good to handle our file upload. So, let's test this endpoint using postman. First, create a new POST request in postman and go to the Body tab. Select form-data and add the following key-value pairs.

operations => { “query”: “mutation ($file: Upload!) { uploadFile(file: $file) }”, “variables”: { “file”: null } }map => { "0": ["variables.file"] }0 => /** choose your file **/
Fully configured postman POST call

Now we are all set to test our endpoint. But when we make the call it fails with the following error 🤕.

GraphQLError: Variable \"$file\" got invalid value {}; Upload value invalid

The reason for this error is since we use graphql-upload, we have to disable the Apollo server’s internal file upload feature. That's why we add “upload: false” in the GraphQLModule import in AppModule 😇.

Finally, we need to configure our application to use graphqlUploadExpress() middleware from graphql-upload. Add following code to bootstrap() in main.ts.

import { NestFactory } from '@nestjs/core';
import { graphqlUploadExpress } from 'graphql-upload';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(graphqlUploadExpress({ maxFileSize: 1000000, maxFiles: 10 }));
await app.listen(parseInt(process.env.APP_PORT));
}
bootstrap();

That's all! 🤘 From 👉 Here you can learn more about the graphql-upload package and its advanced usages.

--

--