question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Getting an empty object {} in server instead of file

See original GitHub issue

Hi, I am getting an empty object in server! can you please tell me what is my problem?

server.js:

app.use(
  "/graphql",
  bodyParser.json(),
  apolloUploadExpress(/* Options */),
  graphqlExpress((req: any) => {
    return {
      schema,
      context: {
        EMP_ID: req.EMP_ID
      }
    };
  })
);

Type Definition:

scalar Upload
type File {
  id: ID!
  path: String!
  filename: String!
  mimetype: String!
  encoding: String!
}

Mutations: uploadFile (file: Upload!): File!

resolvers object:

import { GraphQLUpload } from "apollo-upload-server";
const resolvers = {
  Upload: GraphQLUpload,
  Query: queryResolvers,
  Mutation: mutationsResolvers
};

Resolver: uploadFile: (_: any, { file }) => saveFile.processUpload(file)

saveFile Module:

import * as fs from "fs";
import { logger } from "./index";

const uploadDir = "./uploads";

const storeFS = ({ stream, filename }) => {
  const id = Date.now();
  const path = `${uploadDir}/${id}-${filename}`;
  return new Promise((resolve, reject) =>
    stream
      .on("error", error => {
        if (stream.truncated)
          // Delete the truncated file
          fs.unlinkSync(path);
        reject(error);
      })
      .pipe(fs.createWriteStream(path))
      .on("error", error => reject(error))
      .on("finish", () => resolve({ id, path }))
  );
};

const processUpload = async upload => {
  try {
    console.log(upload);
    const { stream, filename, mimetype, encoding } = await upload;
    console.log(stream, filename, mimetype, encoding);
    return await storeFS({ stream, filename });
  } catch (error) {
    logger.log(error);
  }
};

export const saveFile = {
  processUpload
};

In Client in React Component:

import React from "react";

import { graphql } from "react-apollo";
import gql from "graphql-tag";

const UploadFile = ({ mutate }) => {
  const handleChange = ({
    target: {
      validity,
      files: [file]
    }
  }) => {
    validity.valid &&
      mutate({
        variables: { file }
      });
  };

  return <input type="file" required onChange={handleChange} />;
};

export default graphql(gql`
  mutation($file: Upload!) {
    uploadFile(file: $file) {
      id
      filename
      encoding
      mimetype
      path
    }
  }
`)(UploadFile);

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:2
  • Comments:12 (4 by maintainers)

github_iconTop GitHub Comments

7reactions
saostadcommented, May 4, 2018

thank you, for awesome job! 👍

1reaction
jaydensericcommented, Feb 24, 2019

@SanchiSinghal if your issue is not the same as this issue; you should either keep investigating or raise a new issue explaining specific steps to reproduce a graphql-upload bug. It’s not good etiquette to take over old issues and send notifications to everyone in the hope they will provide you support or do investigative work for you. At the very least, please quote errors and format code blocks (without superfluous code/types pasted in with it) properly in markdown like this:

Error: GraphQL error: The “path” argument must be one of type string, Buffer, or URL. Received type undefined

<input type="file" onChange={e => this.setState({ fileName: e.target.files[0] })} />

As always, the first thing to do is make sure you are using the last versions of the client and graphql-upload packages. If there is still a problem, the next thing to investigate is if the problem is on the client or server. If you use the network activity inspector to verify the client is sending a valid GraphQL multipart request, you know not to bother looking at the client and focus on the server.

Read more comments on GitHub >

github_iconTop Results From Across the Web

File data shows empty object when sent to server but contains ...
I am trying to submit a form using react that contains an image file via axios api. My code looks like ...
Read more >
Can't upload a file from node.js to my route, getting empty ...
I am trying to upload a local file using NodeJs (the file is in the same directory as app.js) to my remote Laravel...
Read more >
How to Check if an Object is Empty in JavaScript – JS Java ...
Note: An object is considered empty when it has no key-value pair. In case you are in a rush, here is a basic...
Read more >
How to Check if an Object is Empty in JavaScript or Node.js
This tutorial shows you how to detect if an object is empty in JavaScript. ... JSON; Iterators; Classes; Numbers; Objects; File System ...
Read more >
empty - Manual - PHP
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found