DEV Community

Cover image for Elevate Your GraphQL API: Mastering File Uploads with Yoga GraphQL
Vaibhav Solanki
Vaibhav Solanki

Posted on • Updated on

Elevate Your GraphQL API: Mastering File Uploads with Yoga GraphQL

Introduction:
GraphQL Yoga is a robust framework that seamlessly integrates file uploads into your GraphQL API workflow, thanks to its support for the GraphQL Multipart Request Specification. By leveraging this feature, you can efficiently handle file uploads and process binary data within GraphQL resolvers via HTTP. In this guide, we'll explore how to harness the capabilities of GraphQL Yoga to elevate your API with file upload functionality.

Key Features:

  1. Seamlessly Consume Uploaded Files:
    With GraphQL Yoga, you can effortlessly consume uploaded files or blobs as WHATWG standard File or Blob objects, similar to those found in the browser's API. This standardized approach simplifies the handling of file uploads, ensuring compatibility across various client applications.

  2. Quick Integration with Client Solutions:
    GraphQL Yoga is compatible with any client that supports the GraphQL Upload specification. Whether you're using Apollo Client, Relay, or another GraphQL client solution, you can seamlessly integrate file uploads into your application workflow.

Implementation Guide:

  1. Getting Started:
    To begin processing file uploads in GraphQL Yoga, start by adding a File scalar to your schema. This simple step sets the stage for seamlessly handling file uploads within your GraphQL API.

  2. Example Code:
    Here's a sample implementation demonstrating how to process file uploads in GraphQL Yoga:

import { createYoga } from 'graphql-yoga'
import { createServer } from 'http'

// Provide your schema
const yoga = createYoga({
  schema: createSchema({
    typeDefs: /* GraphQL */ `
      scalar File

      type Query {
        greetings: String!
      }

      type Mutation {
        saveFile(file: File!): Boolean!
      }
    `,
    resolvers: {
      Query: {
        greetings: () => 'Hello World!'
      },
      Mutation: {
        saveFile: async (_, { file }: { file: File }) => {
          try {
            const fileArrayBuffer = await file.arrayBuffer()
            await fs.promises.writeFile(
              path.join(__dirname, file.name),
              Buffer.from(fileArrayBuffer),
            )
          } catch (e) {
            return false
          }
          return true
        },
      }
    }
  })
})

// Start the server and explore http://localhost:4000/graphql
const server = createServer(yoga)
server.listen(4000, () => {
  console.info('Server is running on http://localhost:4000/graphql')
})
Enter fullscreen mode Exit fullscreen mode
  1. Testing with Curl: After starting the server, you can use Curl to test your endpoint. Here's a sample Curl command for testing file uploads:
curl --location 'http://127.0.0.1:4000/graphql' \
--form 'operations="{ \"query\": \"mutation ($file: File!) { saveFile(file: $file) }\", \"variables\": { \"file\": null } }"' \
--form 'map="{ \"0\": [\"variables.file\"] }"' \
--form '0=@"mytext.txt"'
Enter fullscreen mode Exit fullscreen mode

Conclusion:
By following this guide, you'll unlock the full potential of file uploads in your GraphQL API using Yoga GraphQL. With its seamless integration and robust capabilities, GraphQL Yoga empowers you to enhance your API with efficient file upload functionality, delivering an exceptional user experience for your application.

Top comments (0)