Node js File Upload

File Upload Using GraphQL and Node.js

Overview

This guide explains how to upload a file using a GraphQL mutation in a Node.js application. You will use the graphql-request library for making GraphQL requests and the form-data package to handle the file upload.

Steps to Perform a File Upload

  1. Install Required Packages

    First, install the necessary npm packages:

    npm install graphql-request form-data axios
    
  2. Set Up the GraphQL Mutation

    Your GraphQL mutation should look like this:

    mutation singleUpload($file: Upload!) {
      singleUpload(
        file: $file, 
        entity_id: "your_entity_id", // or representative_id
        file_enum: front_drivers_license
      ) {
        filename
      }
    }
    
  3. Prepare the Upload Function

    Create a Node.js script (upload.js) to handle the file upload:

    const { GraphQLClient, gql } = require('graphql-request');
    const FormData = require('form-data');
    const fs = require('fs');
    const path = require('path');
    const axios = require('axios');
    
    const ENDPOINT = 'https://your-graphql-endpoint.com/graphql';
    const TOKEN = 'your-access-token';
    const ENTITY_ID = 'your_entity_id'; // or representative_id
    
    const query = gql`
      mutation singleUpload($file: Upload!) {
        singleUpload(
          file: $file, 
          entity_id: "${ENTITY_ID}", // or representative_id
          file_enum: front_drivers_license
        ) {
          filename
        }
      }
    `;
    
    async function uploadFile() {
      const form = new FormData();
    
      const operations = JSON.stringify({
        query: `
          mutation singleUpload($file: Upload!) {
            singleUpload(
              file: $file, 
              entity_id: "${ENTITY_ID}", // or representative_id
              file_enum: front_drivers_license
            ) {
              filename
            }
          }
        `,
        variables: {
          file: null
        }
      });
    
      form.append('operations', operations);
    
      const map = JSON.stringify({
        0: ['variables.file']
      });
      form.append('map', map);
    
      const filePath = path.join(__dirname, 'my-fake-file.txt');
      form.append('0', fs.createReadStream(filePath), 'my-fake-file.txt');
    
      try {
        const response = await axios.post(`${ENDPOINT}`, form, {
          headers: {
            ...form.getHeaders(),
            'apollo-require-preflight': true,
            Authorization: `Bearer ${TOKEN}`
          }
        });
    
        console.log('File uploaded successfully:', response.data);
      } catch (error) {
        console.error('Error uploading file:', error);
      }
    }
    
    uploadFile();
    

Example Explanation

  • Endpoint URL: Replace https://your-graphql-endpoint.com/graphql with your actual GraphQL endpoint.
  • Authorization Header: Replace your-access-token with your actual token.
  • File Path: Replace path.join(__dirname, 'my-fake-file.txt') with the path to the file you want to upload.
  • Entity ID: Replace your_entity_id with the actual entity or representative ID required by your mutation.

Example Script

Here's a complete example script with placeholders replaced:

const { GraphQLClient, gql } = require('graphql-request');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');
const axios = require('axios');

const ENDPOINT = 'https://api.example.com/graphql';
const TOKEN = 'your-access-token';
const ENTITY_ID = '12345'; // or representative_id

const query = gql`
  mutation singleUpload($file: Upload!) {
    singleUpload(
      file: $file, 
      entity_id: "${ENTITY_ID}", // or representative_id
      file_enum: front_drivers_license
    ) {
      filename
    }
  }
`;

async function uploadFile() {
  const form = new FormData();

  const operations = JSON.stringify({
    query: `
      mutation singleUpload($file: Upload!) {
        singleUpload(
          file: $file, 
          entity_id: "${ENTITY_ID}", // or representative_id
          file_enum: front_drivers_license
        ) {
          filename
        }
      }
    `,
    variables: {
      file: null
    }
  });

  form.append('operations', operations);

  const map = JSON.stringify({
    0: ['variables.file']
  });
  form.append('map', map);

  const filePath = path.join(__dirname, 'my-fake-file.txt');
  form.append('0', fs.createReadStream(filePath), 'my-fake-file.txt');

  try {
    const response = await axios.post(`${ENDPOINT}`, form, {
      headers: {
        ...form.getHeaders(),
        'apollo-require-preflight': true,
        Authorization: `Bearer ${TOKEN}`
      }
    });

    console.log('File uploaded successfully:', response.data);
  } catch (error) {
    console.error('Error uploading file:', error);
  }
}

uploadFile();

Notes

  • Ensure the file path is correct and accessible.
  • The Authorization header must contain a valid token.
  • The operations and map parameters must be properly formatted JSON strings.

By following these steps, you can successfully upload a file using a GraphQL mutation with Node.js. If you encounter any issues, check the structure of your operations and map parameters, and ensure your file path is correct.