android - Apollo GraphQL - 是否可以执行请求不同字段的相同查询?

标签 android graphql apollo apollo-client apollo-android

我正在使用apollo-android我想知道是否可以采用以下方法:

我在服务器的 schema.json 中定义了一个名为 locations 的查询。它的定义如下:

type locations {
  continents: [Continent!],
  countries: [Country!],
  usaStates: [UsaState!]
}

在 Playground 中尝试此查询效果非常好,它会返回各大洲、国家/地区和美国各州。这是我在 Playground 中定义的查询:

query getLocations {
  locations {
    continents {
      name
      code
    }
    countries {
      name
      code
    }
    usaStates {
      code
      name
    }
  }
}

当然,如果我只请求 que 大陆,它只会返回大陆:

query getLocations {
  locations {
    continents {
      name
      code
    }
}

我的问题是是否可以在客户端部分执行相同的操作。当我在 Android 项目的 api.graphql 文件中定义查询时,我这样做:

query getLocations {
  locations {
    continents {
      name
      code
    }
    countries {
      code
      name
    }
    usaStates {
      code
      name
    }
  }
}

然后,当我在代码中调用它时,结果包含大陆、国家和美国:

GetLocationsQuery builder = GetLocationsQuery.builder().build();

api.query(builder)
    .enqueue(new ApolloCall.Callback<GetLocationsQuery.Data>() {
            @Override
            public void onResponse(@NotNull com.apollographql.apollo.api.Response<GetLocationsQuery.Data> response) {
                apiListener.onFinish(response);
            }

            @Override
            public void onFailure(@NotNull ApolloException e) {
                Log.v("APOLLO", e.toString());
                apiListener.onError(e);
            }
        });

有一种方法可以进行相同的调用,但定义我只想要大陆而不是大陆、国家和美国?

提前谢谢您!

最佳答案

The specification说:

The core GraphQL specification includes exactly two directives, which must be supported by any spec-compliant GraphQL server implementation:

  • @include(if: Boolean) Only include this field in the result if the argument is true.
  • @skip(if: Boolean) Skip this field if the argument is true.

api.graphql 带有跳过指令:

query getLocations($continentsOnly: Boolean) {
  locations {
    continents {
      name
      code
    }
    countries @skip(if: $continentsOnly) {
      code
      name
    }
    usaStates @skip(if: $continentsOnly) {
      code
      name
    }
  }
}

显然,您需要指定ContinuesOnly的值

关于android - Apollo GraphQL - 是否可以执行请求不同字段的相同查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55066836/

相关文章:

android - 尝试使用 ORMLite 编写查询?

javascript - 使用 Kentico Kontent 时,对象数组未按照 CMS 中设置的顺序渲染

angular - 如何在 Strapi、GraphQL 的 where 子句中使用多个 'and' 条件进行查询?

reactjs - 如何从apollo缓存中获取更新的数据

java - 从 Firebase Firestore 将文档的一部分获取到对象中

android - 解决 Android/Java Pattern/Matcher Regex 超长字符串限制

java - 如何将 Graphql 查询解析为 Java 对象

javascript - 为什么我的解析器第一次没有返回?

graphql - 是否可以有部分联合网关?

java - Android Firebase 实时数据库 orderByChild 不起作用