Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send binary data back to client using GraphQL

Tags:

I have a GraphQL server, hosted on express. I want to return images to the client by sending back nodejs buffer objects. How can i config graphql server, to return bytes, instead of json? I don't wish to do this through base64, as the image are large in size.

like image 876
user3162979 Avatar asked Apr 18 '17 13:04

user3162979


People also ask

How do you send responses in GraphQL?

GraphQL requests can be sent via HTTP POST or HTTP GET requests. GET requests must be sent in the following format. The query, variables, and operation are sent as URL-encoded query parameters in the URL. In either request method (POST or GET), only query is required.

Does GraphQL return JSON?

Since the structure of a GraphQL query has anatomy we can expect JSON to be returned from the request in defined ways.

Can we post data using GraphQL?

It is not required to use a dedicated GraphQL client, as it is possible to send a GraphQL query as a POST request using the Fetch API, and this is similar to the process used to submit FormData using the Fetch API.


1 Answers

You have to return JSON, but there's still a way. We're using GraphQL to return images stored in Blob fields in a legacy sql database. We're using sequelize, graphql-sequelize, and graphql-js. We've defined the Blob fields to be String types in our graphql schema and so they come through in the json reply just fine. Then we convert to a buffer before delivering, like

const imgBuffer = new Buffer.from(imgObj.data, 'ascii');

The only problem is we're now having trouble saving image data back to the database via the graphql interface. Our mutation function gives us a syntax error when it finds certain bad unicode characters in the strings, like \U0000 and whatnot (so I found your question looking for a solution to that).

like image 177
steev Avatar answered Sep 19 '22 13:09

steev