Introduction:

    In this GraphQL guide, we’ll explore how to upload a file using GraphQL in a TypeScript, MongoDB, and Node.js environment. We’ll set up the schema and resolver to handle file uploads and store the data in a MongoDB database.

Step 1 : Define the schema for uploading a file

Step 2: Define the Resolver for uploading a file   

In this code, when a file is uploaded, the data is stored in the MongoDB database. The process involves reading the file using fs.createReadStream to create a readable stream from the CSV file and piping the stream through csvParser() to parse the CSV data. For each row of data parsed from the CSV:

  1. It checks if an employee with the same employeID already exists in the database using EmployeModel.findOne.
  2. If an existing employee is found, it deletes the employee using EmployeModel.findByIdAndDelete.
  3. It constructs a new employee object with data from the CSV row.
  4. It creates a new employee record in the database using EmployeModel.create.
  5. After parsing all rows, it deletes the uploaded CSV file using fs.unlinkSync.
  6. It resolves the Promise to indicate completion.


Step 3: Uploading a file in Postman

  1. Open Postman and create a new request.
  2. Set the request type to POST.
  3. Enter the URL of your GraphQL endpoint.
  4. Switch to the Body tab and select form-data.
  5. Add a key-value pair where the key is the same as the variable name specified in your GraphQL query (file), and the value is the file you want to upload. Click on the value field of the added key, and select File.
  6. Click on Select Files and choose the file you want to upload (in this case, file.csv).
  7. Go to the Headers tab and set the Content-Type header to multipart/form-data.
  8. Click Send to execute the request.

Operation:

{ “query”: “mutation UploadFile($file: Upload!) { uploadFile(file: $file) { success message } }”,”variables”: { “file”: “file.csv” } }

Map:

{ “0”: [“variables.file”] }

0: File

Leave a Reply