Skip to content

Commit

Permalink
[productcatalog] - allow products to be extended (open-telemetry#1363)
Browse files Browse the repository at this point in the history
* allow products to be extended

Signed-off-by: Pierre Tessier <[email protected]>

* allow products to be extended

Signed-off-by: Pierre Tessier <[email protected]>

* fix products path

Signed-off-by: Pierre Tessier <[email protected]>

* fix merge conflict

Signed-off-by: Pierre Tessier <[email protected]>

---------

Signed-off-by: Pierre Tessier <[email protected]>
Co-authored-by: Juliano Costa <[email protected]>
  • Loading branch information
puckpuck and julianocosta89 authored Feb 9, 2024
1 parent b8cc894 commit ab6c1a7
Show file tree
Hide file tree
Showing 11 changed files with 62 additions and 27 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ the release.
([#1358](https://github.com/open-telemetry/opentelemetry-demo/pull/1358))
* [loadgenerator] fix browser traffic enabled flag
([#1359](https://github.com/open-telemetry/opentelemetry-demo/pull/1359))
* [productcatalog] allow products to be extended
([#1363](https://github.com/open-telemetry/opentelemetry-demo/pull/1363))

## 1.7.2

Expand Down
2 changes: 1 addition & 1 deletion src/frontend/components/CartDropdown/CartDropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const CartDropdown = ({ productList, isOpen, onClose }: IProps) => {
{productList.map(
({ quantity, product: { name, picture, id, priceUsd = { nanos: 0, currencyCode: 'USD', units: 0 } } }) => (
<S.Item key={id} data-cy={CypressFields.CartDropdownItem}>
<S.ItemImage src={picture} alt={name} />
<S.ItemImage src={"/images/products/" + picture} alt={name} />
<S.ItemDetails>
<S.ItemName>{name}</S.ItemName>
<ProductPrice price={priceUsd} />
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/components/CartItems/CartItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const CartItem = ({
<S.CartItem>
<Link href={`/product/${id}`}>
<S.NameContainer>
<S.CartItemImage alt={name} src={picture} />
<S.CartItemImage alt={name} src={"/images/products/" + picture} />
<p>{name}</p>
</S.NameContainer>
</Link>
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/components/CheckoutItem/CheckoutItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const CheckoutItem = ({
return (
<S.CheckoutItem data-cy={CypressFields.CheckoutItem}>
<S.ItemDetails>
<S.ItemImage src={picture} alt={name} />
<S.ItemImage src={"/images/products/" + picture} alt={name} />
<S.Details>
<S.ItemName>{name}</S.ItemName>
<p>Quantity: {quantity}</p>
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/components/ProductCard/ProductCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const ProductCard = ({
return (
<S.Link href={`/product/${id}`}>
<S.ProductCard data-cy={CypressFields.ProductCard}>
<S.Image $src={picture} />
<S.Image $src={"/images/products/" + picture} />
<div>
<S.ProductName>{name}</S.ProductName>
<S.ProductPrice>
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/pages/product/[productId]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const ProductDetail: NextPage = () => {
<Layout>
<S.ProductDetail data-cy={CypressFields.ProductDetail}>
<S.Container>
<S.Image $src={picture} data-cy={CypressFields.ProductPicture} />
<S.Image $src={"/images/products/" + picture} data-cy={CypressFields.ProductPicture} />
<S.Details>
<S.Name data-cy={CypressFields.ProductName}>{name}</S.Name>
<S.Description data-cy={CypressFields.ProductDescription}>{description}</S.Description>
Expand Down
2 changes: 1 addition & 1 deletion src/productcatalogservice/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ FROM alpine AS release

WORKDIR /usr/src/app/

COPY ./src/productcatalogservice/products.json ./
COPY ./src/productcatalogservice/products/ ./products/
COPY --from=builder /go/bin/productcatalogservice/ ./

EXPOSE ${PRODUCT_SERVICE_PORT}
Expand Down
51 changes: 42 additions & 9 deletions src/productcatalogservice/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ package main
import (
"context"
"fmt"
"io/ioutil"
"io/fs"

"net"
"os"
"strings"
Expand Down Expand Up @@ -51,7 +52,12 @@ var (

func init() {
log = logrus.New()
catalog = readCatalogFile()
var err error
catalog, err = readProductFiles()
if err != nil {
log.Fatalf("Reading Product Files: %v", err)
os.Exit(1)
}
}

func initResource() *sdkresource.Resource {
Expand Down Expand Up @@ -151,18 +157,45 @@ type productCatalog struct {
pb.UnimplementedProductCatalogServiceServer
}

func readCatalogFile() []*pb.Product {
catalogJSON, err := ioutil.ReadFile("products.json")
func readProductFiles() ([]*pb.Product, error) {

// find all .json files in the products directory
entries, err := os.ReadDir("./products")
if err != nil {
log.Fatalf("Reading Catalog File: %v", err)
return nil, err
}

jsonFiles := make([]fs.FileInfo, 0, len(entries))
for _, entry := range entries {
if strings.HasSuffix(entry.Name(), ".json") {
info, err := entry.Info()
if err != nil {
return nil, err
}
jsonFiles = append(jsonFiles, info)
}
}

var res pb.ListProductsResponse
if err := protojson.Unmarshal(catalogJSON, &res); err != nil {
log.Fatalf("Parsing Catalog JSON: %v", err)
// read the contents of each .json file and unmarshal into a ListProductsResponse
// then append the products to the catalog
var products []*pb.Product
for _, f := range jsonFiles {
jsonData, err := os.ReadFile("./products/" + f.Name())
if err != nil {
return nil, err
}

var res pb.ListProductsResponse
if err := protojson.Unmarshal(jsonData, &res); err != nil {
return nil, err
}

products = append(products, res.Products...)
}

return res.Products
log.Infof("Loaded %d products", len(products))

return products, nil
}

func mustMapEnv(target *string, key string) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"id": "OLJCESPC7Z",
"name": "National Park Foundation Explorascope",
"description": "The National Park Foundation’s (NPF) Explorascope 60AZ is a manual alt-azimuth, refractor telescope perfect for celestial viewing on the go. The NPF Explorascope 60 can view the planets, moon, star clusters and brighter deep sky objects like the Orion Nebula and Andromeda Galaxy.",
"picture": "/images/products/NationalParkFoundationExplorascope.jpg",
"picture": "NationalParkFoundationExplorascope.jpg",
"priceUsd": {
"currencyCode": "USD",
"units": 101,
Expand All @@ -16,7 +16,7 @@
"id": "66VCHSJNUP",
"name": "Starsense Explorer Refractor Telescope",
"description": "The first telescope that uses your smartphone to analyze the night sky and calculate its position in real time. StarSense Explorer is ideal for beginners thanks to the app’s user-friendly interface and detailed tutorials. It’s like having your own personal tour guide of the night sky",
"picture": "/images/products/StarsenseExplorer.jpg",
"picture": "StarsenseExplorer.jpg",
"priceUsd": {
"currencyCode": "USD",
"units": 349,
Expand All @@ -28,7 +28,7 @@
"id": "1YMWWN1N4O",
"name": "Eclipsmart Travel Refractor Telescope",
"description": "Dedicated white-light solar scope for the observer on the go. The 50mm refracting solar scope uses Solar Safe, ISO compliant, full-aperture glass filter material to ensure the safest view of solar events. The kit comes complete with everything you need, including the dedicated travel solar scope, a Solar Safe finderscope, tripod, a high quality 20mm (18x) Kellner eyepiece and a nylon backpack to carry everything in. This Travel Solar Scope makes it easy to share the Sun as well as partial and total solar eclipses with the whole family and offers much higher magnifications than you would otherwise get using handheld solar viewers or binoculars.",
"picture": "/images/products/EclipsmartTravelRefractorTelescope.jpg",
"picture": "EclipsmartTravelRefractorTelescope.jpg",
"priceUsd": {
"currencyCode": "USD",
"units": 129,
Expand All @@ -40,7 +40,7 @@
"id": "L9ECAV7KIM",
"name": "Lens Cleaning Kit",
"description": "Wipe away dust, dirt, fingerprints and other particles on your lenses to see clearly with the Lens Cleaning Kit. This cleaning kit works on all glass and optical surfaces, including telescopes, binoculars, spotting scopes, monoculars, microscopes, and even your camera lenses, computer screens, and mobile devices. The kit comes complete with a retractable lens brush to remove dust particles and dirt and two options to clean smudges and fingerprints off of your optics, pre-moistened lens wipes and a bottled lens cleaning fluid with soft cloth.",
"picture": "/images/products/LensCleaningKit.jpg",
"picture": "LensCleaningKit.jpg",
"priceUsd": {
"currencyCode": "USD",
"units": 21,
Expand All @@ -52,7 +52,7 @@
"id": "2ZYFJ3GM2N",
"name": "Roof Binoculars",
"description": "This versatile, all-around binocular is a great choice for the trail, the stadium, the arena, or just about anywhere you want a close-up view of the action without sacrificing brightness or detail. It’s an especially great companion for nature observation and bird watching, with ED glass that helps you spot the subtlest field markings and a close focus of just 6.5 feet.",
"picture": "/images/products/RoofBinoculars.jpg",
"picture": "RoofBinoculars.jpg",
"priceUsd": {
"currencyCode": "USD",
"units": 209,
Expand All @@ -64,7 +64,7 @@
"id": "0PUK6V6EV0",
"name": "Solar System Color Imager",
"description": "You have your new telescope and have observed Saturn and Jupiter. Now you're ready to take the next step and start imaging them. But where do you begin? The NexImage 10 Solar System Imager is the perfect solution.",
"picture": "/images/products/SolarSystemColorImager.jpg",
"picture": "SolarSystemColorImager.jpg",
"priceUsd": {
"currencyCode": "USD",
"units": 175,
Expand All @@ -76,7 +76,7 @@
"id": "LS4PSXUNUM",
"name": "Red Flashlight",
"description": "This 3-in-1 device features a 3-mode red flashlight, a hand warmer, and a portable power bank for recharging your personal electronics on the go. Whether you use it to light the way at an astronomy star party, a night walk, or wildlife research, ThermoTorch 3 Astro Red’s rugged, IPX4-rated design will withstand your everyday activities.",
"picture": "/images/products/RedFlashlight.jpg",
"picture": "RedFlashlight.jpg",
"priceUsd": {
"currencyCode": "USD",
"units": 57,
Expand All @@ -88,7 +88,7 @@
"id": "9SIQT8TOJO",
"name": "Optical Tube Assembly",
"description": "Capturing impressive deep-sky astroimages is easier than ever with Rowe-Ackermann Schmidt Astrograph (RASA) V2, the perfect companion to today’s top DSLR or astronomical CCD cameras. This fast, wide-field f/2.2 system allows for shorter exposure times compared to traditional f/10 astroimaging, without sacrificing resolution. Because shorter sub-exposure times are possible, your equatorial mount won’t need to accurately track over extended periods. The short focal length also lessens equatorial tracking demands. In many cases, autoguiding will not be required.",
"picture": "/images/products/OpticalTubeAssembly.jpg",
"picture": "OpticalTubeAssembly.jpg",
"priceUsd": {
"currencyCode": "USD",
"units": 3599,
Expand All @@ -100,7 +100,7 @@
"id": "6E92ZMYYFZ",
"name": "Solar Filter",
"description": "Enhance your viewing experience with EclipSmart Solar Filter for 8” telescopes. With two Velcro straps and four self-adhesive Velcro pads for added safety, you can be assured that the solar filter cannot be accidentally knocked off and will provide Solar Safe, ISO compliant viewing.",
"picture": "/images/products/SolarFilter.jpg",
"picture": "SolarFilter.jpg",
"priceUsd": {
"currencyCode": "USD",
"units": 69,
Expand All @@ -112,7 +112,7 @@
"id": "HQTGWGPNH4",
"name": "The Comet Book",
"description": "A 16th-century treatise on comets, created anonymously in Flanders (now northern France) and now held at the Universitätsbibliothek Kassel. Commonly known as The Comet Book (or Kometenbuch in German), its full title translates as “Comets and their General and Particular Meanings, According to Ptolomeé, Albumasar, Haly, Aliquind and other Astrologers”. The image is from https://publicdomainreview.org/collection/the-comet-book, made available by the Universitätsbibliothek Kassel under a CC-BY SA 4.0 license (https://creativecommons.org/licenses/by-sa/4.0/)",
"picture": "/images/products/TheCometBook.jpg",
"picture": "TheCometBook.jpg",
"priceUsd": {
"currencyCode": "USD",
"units": 0,
Expand Down
2 changes: 1 addition & 1 deletion test/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ ENV NODE_ENV production
COPY --chown=node:node --from=build /app/node_modules/ ./node_modules/
COPY ./test ./
COPY ./pb/demo.proto ./
COPY ./src/productcatalogservice/products.json ../src/productcatalogservice/products.json
COPY ./src/productcatalogservice/products/products.json ../src/productcatalogservice/products/products.json

ENTRYPOINT ["npm", "test"]
2 changes: 1 addition & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const protoLoader = require("@grpc/proto-loader");
const fetch = require("node-fetch");
const dotenvExpand = require("dotenv-expand");
const { resolve } = require("path");
const productData = require("../src/productcatalogservice/products.json");
const productData = require("../src/productcatalogservice/products/products.json");

const myEnv = dotEnv.config({
path: resolve(__dirname, "../.env"),
Expand Down

0 comments on commit ab6c1a7

Please sign in to comment.