Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for How To Upload Files With GraphQl And NestJs
Amine Elbarry
Amine Elbarry

Posted on

     

How To Upload Files With GraphQl And NestJs

Quick demonstration on using GraphQL and Nestjs to upload files (NestJs Code First Approch)

Overview

Hi 👋 You, Today, I'm going to discuss how to upload files using graphql. You may already be familiar with how to upload files using the Rest API, but now you tried Graphql and you're wondering how to upload your cat pictures.

If you're using Nest Js and the Code-first GraphQL approch this guide is for you

Setup

Let's start by installing our dependencies

npm i @nestjs/graphql @nestjs/apollo graphql apollo-server-express graphql-upload@14yarn add @nestjs/graphql @nestjs/apollo graphql apollo-server-express graphql-upload@14
Enter fullscreen modeExit fullscreen mode

Now everything is installed go to yourapp.module.ts file and import ApolloDriver, ApolloDriverConfig & GraphQLModule.

import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';import { GraphQLModule } from '@nestjs/graphql';
Enter fullscreen modeExit fullscreen mode

Then add GraphQLModule config to the App module imports.

@Module({imports: [  GraphQLModule.forRoot<ApolloDriverConfig>({  driver: ApolloDriver,  autoSchemaFile: join(process.cwd(), 'src/schema.gql'), }),],
Enter fullscreen modeExit fullscreen mode

Lets generate our graphql code now by using nest cli in our terminal.

nest g resource cats
Enter fullscreen modeExit fullscreen mode

Now Select GraphQL (code first)

? What transport layer do you use?  REST API  GraphQL (code first)  GraphQL (schema first)  Microservice (non-HTTP)  WebSockets
Enter fullscreen modeExit fullscreen mode

This will create a folder inside yousrc Directory calledcats.

Let's Code

Now let's start by writing our mutation to create a cat object with an image

let's start by editing ourcreateCatInput which is imported by ourcreateCatmutation

@InputType()export class CreateCatInput {  @Field(() => Int, { description: 'Example field (placeholder)' })  exampleField: number;}
Enter fullscreen modeExit fullscreen mode

Our cat will have these properties name, breed & image

Create a file upload type that we can use for our image field which look like this

import { Stream } from 'stream';export interface FileUpload {  filename: string;  mimetype: string;  encoding: string;  createReadStream: () => Stream;}
Enter fullscreen modeExit fullscreen mode

Now Add The Fields With GraphQLUpload Scalar Type wich is imported from our packagegraphql-upload which gives us support for GraphQL multipart requests.

import * as GraphQLUpload from 'graphql-upload/GraphQLUpload.js';@InputType()export class CreateCatInput {  @Field(() => String)  name: string;  @Field(() => String)  breed: string;  @Field(() => GraphQLUpload)  image: Promise<FileUpload>;}
Enter fullscreen modeExit fullscreen mode

Then head to the cat entity and create a similar type and modify the image field as string so we can return just the filename

@ObjectType()export class Cat {  @Field(() => String)  name: string;  @Field(() => String)  breed: string;  @Field(() => String)  image: string;}
Enter fullscreen modeExit fullscreen mode

Ok now we go to ourcats.service.ts where we can handle our image.

create({ breed, name, image }: CreateCatInput) {  // your code goes here}
Enter fullscreen modeExit fullscreen mode

We will return the breed and name precisely as we received them.readable stream ( image ) go ahead and create a new folder, you can name itupload,we will save our images inside it.

async create({ breed, name, image }: CreateCatInput) {  const { createReadStream, filename } = await image;  return new Promise(async (resolve) => {  createReadStream()   .pipe(createWriteStream(join(process.cwd(), `./src/upload/${filename}`)))   .on('finish', () =>     resolve({      breed,      name,      image: filename,     }),   )   .on('error',() => {       new HttpException('Could not save image', HttpStatus.BAD_REQUEST);    });  });}
Enter fullscreen modeExit fullscreen mode

Finally go toapp.module.ts and add GraphQLUpload Middleware

import * as graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js';const app = await NestFactory.create(AppModule);app.use(graphqlUploadExpress({ maxFileSize: 1000000, maxFiles: 10 }));await app.listen(4000);
Enter fullscreen modeExit fullscreen mode

Complete Reading on myportfolio

Top comments(5)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
chamarapw profile image
ChamaraPW
  • Joined
• Edited on• Edited

I followed this artical to create fileupload end point but getting this errorcreateReadStream is not a function

CollapseExpand
 
elbarryamine profile image
Amine Elbarry
I'm Amine Elbarry,

can you share your code with me i can help you with that

CollapseExpand
 
timmyrb profile image
Jacob Brasil
  • Joined

I'm having an issue where the image is an empty file with the correct name in .src/upload, and when I log the readStream, the length is 0. I have tried with multiple images, any ideas why this could be?

CollapseExpand
 
ricka7x profile image
Ricardo Enciso
Just a guy whose passionate about technology
  • Location
    Mexico
  • Work
    React Engineer at people thrust
  • Joined

nice!!! just one question though... is there a problem with current version of graphql-upload or why use version @14 ?

CollapseExpand
 
elbarryamine profile image
Amine Elbarry
I'm Amine Elbarry,

yes there is i had some issues with it

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I'm Amine Elbarry,
  • Location
    Morocco
  • Work
    Software engineer
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp