NestJS GraphQL File Upload
February 07, 2020
Usage of graphql-upload
Setup a NestJS app with the CLI:
Configure GraphQL:
In the root of the app, outside the src
directory, create a directory named uploads
to write the uploaded file
Create a Resolver for the upload
import { Resolver, Args, Mutation } from '@nestjs/graphql';
import { GraphQLUpload, FileUpload } from 'graphql-upload';
import { createWriteStream } from 'fs';
@Resolver()
export class FileResolver {
constructor() {}
@Mutation(() => Boolean)
async uploadFile(@Args({name: 'file', type: () => GraphQLUpload})
{
createReadStream,
filename
}: FileUpload): Promise<boolean> {
return new Promise(async (resolve, reject) =>
createReadStream()
.pipe(createWriteStream(`./uploads/${filename}`))
.on('finish', () => resolve(true))
.on('error', () => reject(false))
);
}
}
NestJS
has a wrapper around Apollo 2 server.graphql-upload
along with theUpload
scalar come with Apollo version 2
Test this in Postman
- Select
POST
from the dropdown - Enter url to Graph server i.e.
http://localhost:5000/graphql
- Select
form-data
and theBody
tab - Fill out the
Body
tab as follows
Key | Value |
---|---|
operations | {“query”:“mutation UploadFile($file:Upload!) {\n uploadFile(file:$file)\n}”, “variables”: { “file”: null }} |
map | { “0”: [“variables.file”] } |
0 | [File ▾] (select your file to upload) |
- Once the body is filled out click
Send
Successful response
{
"data": {
"uploadFile": true
}
}
File should now be in the /uploads
folder in the app root