Implementing the sort interface for the product model

Before we get started, we will define a new type called Products (in the shared/models/product.go source file), which will be a slice of Product objects:

type Products []*Product

We will have the Products type implement the sort interface by defining the following methods:

func (p Products) Len() int { return len(p) }
func (p Products) Less(i, j int) bool { return p[i].Price < p[j].Price }
func (p Products) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

By examining the Less method, you will be able to see that we will sort the products displayed on the product listing page by the product's price in ascending order (lowest to highest).

At the first glance we may presume that the products obtained from the Redis database are already sorted in some predetermined order. However, if we want isomorphic handoff to succeed, we cannot operate in the realm of assumption; we must operate in the realm of fact. In order to do so, we need a predictable criteria for the sorting of products.

This is why we perform the additional work of implementing the sort interface for the Products type, so that we have a predictable criteria by which the products are listed on the products listing page. It provides us a benchmark when verifying the success of isomorphic handoff, since we simply need to confirm that the products listing page rendered on the client side is identical to the products listing page rendered on the server side. It is indeed helpful, that we have a common, predictable criteria that the products are sorted by price in the ascending order.

We add the following line (shown in bold) in the GetProducts method in the redis.go source file to sort the products:

func (r *RedisDatastore) GetProducts() []*models.Product {

registryKey := "product-registry"
exists, err := r.Cmd("EXISTS", registryKey).Int()

if err != nil {
log.Println("Encountered error: ", err)
return nil
} else if exists == 0 {
return nil
}

var productKeys []string
jsonData, err := r.Cmd("GET", registryKey).Str()
if err != nil {
log.Print("Encountered error when attempting to fetch product registry data from Redis instance: ", err)
return nil
}

if err := json.Unmarshal([]byte(jsonData), &productKeys); err != nil {
log.Print("Encountered error when attempting to unmarshal JSON product registry data: ", err)
return nil
}

products := make(models.Products, 0)

for i := 0; i < len(productKeys); i++ {

productTitle := strings.Replace(productKeys[i], "/product-detail/", "", -1)
product := r.GetProductDetail(productTitle)
products = append(products, product)

}
sort.Sort(products)
return products
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.179.220