【问题标题】:How to run a graphql against faunadb from html client如何从 html 客户端运行 graphql
【发布时间】:2021-01-03 08:54:38
【问题描述】:

我对 graphql 和 Florencedb 完全陌生,所以如果这是一个愚蠢的问题,请多多包涵。 我看到我可以从仪表板 > GRAPHQL 运行 graphql 查询。例如粘贴以下代码

query FindAllTodos {
  allTodos {
    data {
      _id
      title
      completed
      list {
        title
      }
    }
  }
}

然后点击运行按钮。但是如何从我想在浏览器中运行的 html/js 代码运行这个查询呢? 在 js 中我可以创建 clientsdk 但不知道如何通过上述查询?

import faunadb, { query as q } from 'faunadb';
let adminClient = new faunadb.Client({
  secret: 'my-key'
});

在谷歌搜索中,我发现了一些使用类似 FQL 的结构的示例

adminClient.query(
      q.Get(q.Ref(q.Collection('Todo'), '276653641074475527'))
    )
    .then((ret) => console.log(ret));

但是我如何才能通过 graphql 查询并获得相同的结果,它在 graphql 操场的右侧窗格中返回我。

【问题讨论】:

    标签: graphql faunadb


    【解决方案1】:

    您可以使用 curl 之类的客户端或任何 GraphQL 客户端。 使用 curl 你可以发出类似:

    curl -X POST -H 'Authorization: Bearer <your key>' https://graphql.fauna.com/graphql -d '{ "query": "{ FindAllTodos{ data {_id title completed list { title }} }}"}'
    

    【讨论】:

      【解决方案2】:

      我可以让你达到 90%,但我提供给你的代码是用 TypeScript 在一个使用 HttpClient 和 RxJs Observables 的 Angular 应用程序中编写的。稍加努力,您就可以使用 vanilla HTTP fetch 在 JS 中重写。

      顺便说一下,这是 Brecht De Rooms 的一段视频,对我帮助很大: https://www.youtube.com/watch?v=KlUPiQaTp0I

        const SERVER_KEY = 'Your server key goes here';
      
        const executeQuery = (query: string) => {
          const headers = new HttpHeaders().set('Authorization', 'Bearer ' + SERVER_KEY);
          return this.http.post<any>('https://graphql.fauna.com/graphql',
            JSON.stringify({ query }), { headers });
        }
      
        const findAllTodos = () => {
          const query = `query FindAllTodos {
            allTodos {
              data {
                _id
                title
                completed
                list {
                  title
                }
              }
            }
          }`;
          return executeQuery(query);
        }
      
        findAllTodos().subscribe(console.log);
      

      对我来说,障碍是了解 Fauna 服务器需要这种形式的 JSON:

      { "query": "query FindAllTodos {allTodos { ... and so forth and so on ..." }
      

      当你运行一个突变时,同样的结构也适用:

      { "query": "mutation AddTodo { ...etc... " }
      

      顺便说一句,如果您的查询在第一次时不起作用(可能不会),我建议您打开浏览器的开发人员工具的网络选项卡并检查发送到 Fauna 服务器的请求。查看响应。里面会有错误信息。即使有错误,响应状态也会是 200(OK)。您需要查看响应以检查错误。

      【讨论】:

        猜你喜欢
        • 2021-05-30
        • 2023-03-15
        • 2018-01-23
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 2021-05-04
        • 2022-11-28
        • 1970-01-01
        相关资源
        最近更新 更多