34

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!

Edd Chang
  • 931
  • 1
  • 7
  • 16

2 Answers2

55

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.

tvStatic
  • 921
  • 1
  • 9
  • 26
galkin
  • 5,264
  • 3
  • 34
  • 51
2

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
Masih Jahangiri
  • 9,489
  • 3
  • 45
  • 51
  • 1
    So what you mean to say is, that everytime a user requests a file, the server saves it locally and hashes it while generating a temporary link the user can then use to download it if need be. This link survives for, lets say, a few hours and many users can download it if they have access to it, and after it expires, a new one is generated whenever a new user requests for it again? – Edd Chang Nov 22 '21 at 09:32
  • can you give code example for how to save file, hash it in the server and make a temporary link out of it ? – Itay Tur Dec 11 '22 at 10:55