0

I am implementing a graphQL server using Apollo server. I want to send the response of the queries as a text file instead of JSON response. Can anyone help me how to do it in Apollo server.I am using NodeJS for server implementation.

  • Did helped you my Answer or not ? – Rebai Ahmed Nov 25 '19 at 13:52
  • Thank you for the answer. I did try this. But for Apollo server this didn't work. – Cleevan Alban Cardoza Nov 25 '19 at 18:07
  • I'm coming up with a more complete answer for now but, this is not possible with `graphqlHTTP`. Instead, you need the raw `graphql` library, or some other way to manually query so we can (temporarily) save the result in a variable. Then, either create a temporary file or directly send as buffer, and optionally set `Content-Disposition` header to `attachment; filename=response.json`. Or if at all possible, just set `Content-Disposition: attachment; filename=result.json` – ionizer Dec 06 '19 at 12:40

2 Answers2

0

If you would like to use Apollo Server instead of the vanilla graphql library, try adding a plugin into plugins config:

const server = new ApolloServer({
  typeDefs,
  resolvers,

  // You can import plugins or define them in-line, as shown:
  plugins: [
    {
      requestWillStart(reqCtx) {
        return {
          willSendResponse(ctx) {
            ctx.response.http.headers.set('Content-Disposition', 'attachment; filename=result.json');
          }
        }
      }
    }
  ],
})

Reference: https://www.apollographql.com/docs/apollo-server/integrations/plugins/#willsendresponse

ionizer
  • 1,661
  • 9
  • 22
-3

For sending File with app Express js :

app.get('/URL', (req, res) => res.download('./yourFile.txt'))

And to write your graphql query result to yourFile.txt

var fs = require("fs");

var data = "your_data_graphql";

fs.writeFile("temp.txt", data, (err) => {
  if (err) console.log(err);
  console.log("Successfully Written to File.");
});
Rebai Ahmed
  • 1,509
  • 1
  • 14
  • 21