Guides / Building Search UI / Ecommerce ui template / Components / Data sources

The ProductRepository component implements the repository design pattern and includes methods to fetch product information. It encapsulates the [Algolia client][https://pub.dev/packages/algolia].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class ProductRepository {
  ProductRepository._internal();

  static final ProductRepository _instance = ProductRepository._internal();

  factory ProductRepository() {
    return _instance;
  }

  final Algolia _algoliaClient = Algolia.init(
      applicationId: Credentials.applicationID,
      apiKey: Credentials.searchOnlyKey);

  /// Get products list by query.
  Future<List<Product>> getProducts(Query query) async {
    final response = await searchProducts(query);
    return response.hits ?? List.empty();
  }

  /// Get product by ID.
  Future<Product> getProduct(String productID) async {
    List<AlgoliaObjectSnapshot> products = await _algoliaClient.instance
        .index(Credentials.hitsIndex)
        .getObjectsByIds([productID]);
    final product = Product.fromJson(products.first.toMap());
    return product;
  }

  /// Get list of seasonal products.
  Future<List<Product>> getSeasonalProducts() async {
    final response = await searchProducts(
        Query('', ruleContexts: ['home-spring-summer-2021']));
    return response.hits ?? List.empty();
  }

  /// Search products by query.
  Future<SearchResponse> searchProducts(Query query) async {
    AlgoliaQuery algoliaQuery =
        _algoliaClient.instance.index(Credentials.hitsIndex);
    algoliaQuery = query.apply(algoliaQuery);
    AlgoliaQuerySnapshot snap = await algoliaQuery.getObjects();
    return SearchResponse.fromJson(snap.toMap());
  }
}
Did you find this page helpful?