Return file from GraphQL resolve

22,004

Solution 1

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.

Solution 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
Share:
22,004

Related videos on Youtube

Edd Chang
Author by

Edd Chang

Updated on July 09, 2022

Comments

  • Edd Chang
    Edd Chang almost 2 years

    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
    Edd Chang over 2 years
    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?