How to send a file from Node.js to GraphQL API which is using graphql-upload library

Viewed 579

I am trying to send a file from Node.js script to GraphQL server also running on Node, using ApolloServer and Upload type from GraphQLUpload library (I am importing GraphQLUpload named import from the library and passing it to resolvers).

I made following script to do that

import { createApolloFetch } from 'apollo-fetch'
import { createReadStream } from 'fs'

const [_bin, _script, filename] = process.argv

const file = createReadStream(filename)

const query = `
  mutation ChangeAvatar($file: Upload!) {
    changeAvatar(avatar: $file) {
      id
    }
  }
`

const variables = { file }

const fetch = createApolloFetch({ uri: 'http://localhost:4000' })

fetch({ query, variables })
  .then(r => console.log(r))
  .catch(e => console.log(e))

However running the script results with an error:

PS C:\Users\kkm\Workspace\app> ts-node .\scripts\fileUpload.ts .\schema.graphql
{
  errors: [
    {
      message: 'Variable "$file" got invalid value { _readableState: { objectMode: false, highWaterMark: 65536, buffer: [Object], length: 0, pipes: null, pipesCount: 0, flowing: null, ended: false, endEmitted: false, reading: false, sync: true, needReadable: false, emittedReadable: false, readableListening: false, resumeScheduled: false, paused: true, emitClose: false, autoDestroy: false, destroyed: false, defaultEncoding: "utf8", awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, _events: {}, _eventsCount: 1, path: ".\\\\schema.graphql", fd: null, flags: "r", mode: 438, end: null, autoClose: true, bytesRead: 0, closed: false }; Expected type Upload. Upload value invalid.',
      locations: [Array],
      extensions: [Object]
    }
  ],
  extensions: {
    tracing: {
      version: 1,
      startTime: '2020-05-14T15:06:36.197Z',
      endTime: '2020-05-14T15:06:36.198Z',
      duration: 578200,
      execution: [Object]
    }
  }
}

I guess it MAY be caused by incompatibility between new File() method aviable in browser and result of createReadStream()

Are there any libraries which will allow me to send browser-like file from node, or other ways to make this file be passed to resolver?

0 Answers
Related