【问题标题】:Get random element from Graphcool?从 Graphcool 获取随机元素?
【发布时间】:2018-04-18 20:13:16
【问题描述】:

是否可以从Graphcool 后端返回随机 graphql 元素?如果是这样,如何做到这一点?

或者,关于如何为 Graphcool 后端创建自定义查询的任何提示?

【问题讨论】:

    标签: graphql graphcool


    【解决方案1】:

    最好的方法是使用 API Gateway 模式。

    这种方法的想法是将网关服务器放在 Graphcool 的 CRUD API 之上,从而自定义 API。使用这种方法,您需要编写一个额外的 resolver function 来为您检索随机元素:

    const extendTypeDefs = `
      extend type Query {
        randomItem: Item
      }
    `
    
    const mergedSchemas = mergeSchemas({
      schemas: [graphcoolSchema, extendTypeDefs],
      resolvers: mergeInfo => ({
        Query: {
          randomItem: {
            resolve: () => {
              return request(endpoint, allItemsQuery).then(data => {
                const { count } = data._allItemsMeta
                const randomIndex = Math.floor((Math.random() * (count-1)) + 0)
                const { id } = data.allItems[randomIndex]
                return request(endpoint, singleItemQuery, { id }).then(data => data.Item)
              })
            },
          }
        },
      }),
    })
    

    我创建了这个here 的完整示例。如果您有任何其他问题,请告诉我:)

    【讨论】:

    • 谢谢。一直在操场上尝试不同的方法来编写可以这样做的查询,但从来没有用过。
    • 有没有办法让模块在本机反应中工作?或者这会大大改变代码吗?继续说 graphql 工具不是为 React Native 制作的。
    • 这段代码不应该存在于客户端,而是存在于服务器端。
    • 嘿@Michal,感谢您的反馈:) 我从答案中删除了断开的链接。此外,公开该查询的 GraphQL 服务器可以轻松部署到 AWS Lambda 或其他一些 sls 提供商,所以我认为它是无服务器的 ?
    • 感谢您的努力 :) 我不是故意粗鲁的。您的答案可能是 OP 为了从 graphcool 获取随机项目可以做的最好的事情。但是,目前无法实现纯 graphcool 解决方案(没有任何服务器配置)。
    猜你喜欢
    • 2022-01-22
    • 2015-09-22
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    相关资源
    最近更新 更多