getCollectionById method

Future<Collection?> getCollectionById(
  1. String collectionId, {
  2. List<MetafieldIdentifier>? metafields,
})

Returns a collection by id.

Implementation

Future<Collection?> getCollectionById(
  String collectionId, {
  List<MetafieldIdentifier>? metafields,
}) async {
  final WatchQueryOptions _options = WatchQueryOptions(
    document: gql(getCollectionsByIdsQuery),
    variables: {
      'ids': [collectionId],
      'metafields': metafields != null
          ? metafields.map((e) => e.toJson()).toList()
          : [],
    },
    fetchPolicy: ShopifyConfig.fetchPolicy,
  );
  final QueryResult result = await _graphQLClient!.query(_options);
  checkForError(result);
  // `nodes(ids:)` yields [null] for an id that doesn't resolve. Detect that
  // explicitly and return null only for a genuine "not found" — this used to
  // be reached by letting the parse throw and swallowing it, which made a
  // failed request (bad token, no connectivity) indistinguishable from a
  // missing collection.
  final nodes = result.data?['nodes'] as List?;
  if (nodes == null || nodes.isEmpty || nodes.first == null) return null;
  return Collection.fromGraphJson(result.data!);
}