【问题标题】:How to send the result of graphql query as a file?如何将graphql查询的结果作为文件发送?
【发布时间】:2020-03-20 10:08:51
【问题描述】:

我正在使用 Apollo 服务器实现一个 graphQL 服务器。我想将查询的响应作为文本文件而不是 JSON 响应发送。谁能帮助我如何在 Apollo 服务器中执行此操作。我正在使用 NodeJS 进行服务器实现。

【问题讨论】:

  • 我的回答对你有帮助吗?
  • 感谢您的回答。我确实试过这个。但是对于 Apollo 服务器,这不起作用。
  • 我现在想出一个更完整的答案,但是 graphqlHTTP 不可能做到这一点。相反,您需要原始的graphql 库,或其他一些手动查询的方式,以便我们可以(临时)将结果保存在变量中。然后,要么创建一个临时文件,要么直接作为缓冲区发送,并可选择将Content-Disposition 标头设置为attachment; filename=response.json。或者如果可能的话,只需设置Content-Disposition: attachment; filename=result.json

标签: graphql graphql-js apollo-server express-graphql


【解决方案1】:

使用 app Express js 发送文件:

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

并将您的 graphql 查询结果写入 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.");
});

【讨论】:

    【解决方案2】:

    如果您想使用 Apollo Server 而不是原版的 graphql 库,请尝试将插件添加到 plugins 配置中:

    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');
              }
            }
          }
        }
      ],
    })
    

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

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 2015-05-14
      • 1970-01-01
      • 2019-01-01
      • 2017-07-21
      • 2014-06-08
      • 2019-06-13
      • 2021-09-12
      相关资源
      最近更新 更多