Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return file from GraphQL resolve

Tags:

I am currently working on an application with the current tech stack:

Backend:

  • Mongoose

  • Express

  • Apollo

  • GraphQL

Frontend:

  • Vuejs

  • Apollo

  • GraphQL

I have succeeded in uploading files to the server using GraphQL, what I am stuck with is how to implement the 'download' feature. With a normal RESTApi endpoint I can use res.download(filePath) and it works. How do I do this with GraphQL since I don't want to use REST.

Or is there any other standard to go by in this scenario?

Thanks!

like image 897
Edd Chang Avatar asked Mar 04 '19 12:03

Edd Chang


People also ask

Does GraphQL return JSON?

After being validated, a GraphQL query is executed by a GraphQL server which returns a result that mirrors the shape of the requested query, typically as JSON.

Can GraphQL download file?

the Graphql responses JSON format only if you like to download files in the front end you can implement another app like express to upload and download files from/to it.

What is a Gql resolver?

Resolver is a collection of functions that generate response for a GraphQL query. In simple terms, a resolver acts as a GraphQL query handler. Every resolver function in a GraphQL schema accepts four positional arguments as given below − fieldName:(root, args, context, info) => { result }


2 Answers

GraphQL uses JSON format, which represents as text format, not as binary.

If you don't want download files with REST, then you should:

  1. Encode your file content into base64 string in the back end. Related question
  2. Send this string as part of query response.
  3. Save encoded base64 string as a file in the front end. Related question

But right architecture design is add a file link in the GraphQL response and use browser for downloading/rendering the file.

like image 115
galkin Avatar answered Sep 16 '22 12:09

galkin


It's better to send a hashed & temporary link to download it

  1. Save the file and hash the name on your static server (to limit access to other users)
  2. The file should be temporary and should expire in a short time
  3. Send the link of the file in response to API
like image 21
Masih Jahangiri Avatar answered Sep 18 '22 12:09

Masih Jahangiri