Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #586: Pass categories as an input for Ad service #600

Merged
merged 3 commits into from
Nov 26, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,5 @@ significant modifications will be credited to OpenTelemetry Authors.
([#583](https://github.com/open-telemetry/opentelemetry-demo/pull/583))
* Change ZipCode data type from int to string
([#587](https://github.com/open-telemetry/opentelemetry-demo/pull/587))
* Pass product's `categories` as an input for the Ad service
([#600](https://github.com/open-telemetry/opentelemetry-demo/pull/600))
5 changes: 2 additions & 3 deletions src/frontend/components/Ad/Ad.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import { useAd } from '../../providers/Ad.provider';
import * as S from './Ad.styled';

const Ad = () => {
const {
adList: [{ text, redirectUrl } = { text: '', redirectUrl: '' }],
} = useAd();
const { adList } = useAd();
const { text, redirectUrl } = adList[Math.floor(Math.random() * adList.length)] || { text: '', redirectUrl: '' };

return (
<S.Ad data-cy={CypressFields.Ad}>
Expand Down
4 changes: 2 additions & 2 deletions src/frontend/gateways/Api.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,11 @@ const ApiGateway = () => ({
},
});
},
listAds(productIds: string[]) {
listAds(contextKeys: string[]) {
return request<Ad[]>({
url: `${basePath}/data`,
queryParams: {
productIds,
contextKeys,
},
});
},
Expand Down
4 changes: 2 additions & 2 deletions src/frontend/gateways/rpc/Ad.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ const { AD_SERVICE_ADDR = '' } = process.env;
const client = new AdServiceClient(AD_SERVICE_ADDR, ChannelCredentials.createInsecure());

const AdGateway = () => ({
listAds(productIds: string[]) {
listAds(contextKeys: string[]) {
return new Promise<AdResponse>((resolve, reject) =>
client.getAds({ contextKeys: productIds }, (error, response) => (error ? reject(error) : resolve(response)))
client.getAds({ contextKeys: contextKeys }, (error, response) => (error ? reject(error) : resolve(response)))
);
},
});
Expand Down
4 changes: 2 additions & 2 deletions src/frontend/pages/api/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ type TResponse = Ad[] | Empty;
const handler = async ({ method, query }: NextApiRequest, res: NextApiResponse<TResponse>) => {
switch (method) {
case 'GET': {
const { productIds = [] } = query;
const { ads: adList } = await AdGateway.listAds(productIds as string[]);
const { contextKeys = [] } = query;
const { ads: adList } = await AdGateway.listAds(Array.isArray(contextKeys) ? contextKeys : contextKeys.split(','));

return res.status(200).json(adList);
}
Expand Down
11 changes: 9 additions & 2 deletions src/frontend/pages/cart/checkout/[orderId]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ const Checkout: NextPage = () => {
const { items = [], shippingAddress } = JSON.parse((query.order || '{}') as string) as IProductCheckout;

return (
<AdProvider productIds={items.map(({ item }) => item?.productId || '')}>
<AdProvider
productIds={items.map(({ item }) => item?.productId || '')}
contextKeys={[...new Set(items.flatMap(({ item }) => item.product.categories))]}
>
<Layout>
<S.Checkout>
<S.Container>
Expand All @@ -25,7 +28,11 @@ const Checkout: NextPage = () => {

<S.ItemList>
{items.map(checkoutItem => (
<CheckoutItem key={checkoutItem.item.productId} checkoutItem={checkoutItem} address={shippingAddress!} />
<CheckoutItem
key={checkoutItem.item.productId}
checkoutItem={checkoutItem}
address={shippingAddress!}
/>
))}
</S.ItemList>

Expand Down
5 changes: 4 additions & 1 deletion src/frontend/pages/cart/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ const Cart: NextPage = () => {
} = useCart();

return (
<AdProvider productIds={items.map(({ productId }) => productId)}>
<AdProvider
productIds={items.map(({ productId }) => productId)}
contextKeys={[...new Set(items.flatMap(({ product }) => product.categories))]}
>
<Layout>
<S.Cart>
{(!!items.length && <CartDetail />) || <EmptyCart />}
Expand Down
13 changes: 11 additions & 2 deletions src/frontend/pages/product/[productId]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,13 @@ const ProductDetail: NextPage = () => {
const productId = query.productId as string;

const {
data: { name, picture, description, priceUsd = { units: 0, currencyCode: 'USD', nanos: 0 } } = {} as Product,
data: {
name,
picture,
description,
priceUsd = { units: 0, currencyCode: 'USD', nanos: 0 },
categories,
} = {} as Product,
} = useQuery(
['product', productId, 'selectedCurrency', selectedCurrency],
() => ApiGateway.getProduct(productId, selectedCurrency),
Expand All @@ -48,7 +54,10 @@ const ProductDetail: NextPage = () => {
}, [addItem, productId, quantity, push]);

return (
<AdProvider productIds={[productId, ...items.map(({ productId }) => productId)]}>
<AdProvider
productIds={[productId, ...items.map(({ productId }) => productId)]}
contextKeys={[...new Set(categories)]}
>
<Layout>
<S.ProductDetail data-cy={CypressFields.ProductDetail}>
<S.Container>
Expand Down
19 changes: 15 additions & 4 deletions src/frontend/providers/Ad.provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,26 @@ export const Context = createContext<IContext>({
interface IProps {
children: React.ReactNode;
productIds: string[];
contextKeys: string[];
}

export const useAd = () => useContext(Context);

const AdProvider = ({ children, productIds }: IProps) => {
const AdProvider = ({ children, productIds, contextKeys }: IProps) => {
const { selectedCurrency } = useCurrency();
const { data: adList = [] } = useQuery(['ads', productIds], () => ApiGateway.listAds(productIds), {
refetchOnWindowFocus: false,
});
const { data: adList = [] } = useQuery(
['ads', contextKeys],
() => {
if (contextKeys.length === 0) {
return Promise.resolve([]);
} else {
return ApiGateway.listAds(contextKeys);
}
},
{
refetchOnWindowFocus: false,
}
);
const { data: recommendedProductList = [] } = useQuery(
['recommendations', productIds, 'selectedCurrency', selectedCurrency],
() => ApiGateway.listRecommendations(productIds, selectedCurrency),
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "es5",
"target": "ES2015",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
Expand Down
10 changes: 9 additions & 1 deletion src/loadgenerator/locustfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@
RequestsInstrumentor().instrument()
URLLib3Instrumentor().instrument()

categories = [
"binoculars",
"telescopes",
"accessories",
"assembly",
"travel",
]

products = [
"0PUK6V6EV0",
"1YMWWN1N4O",
Expand Down Expand Up @@ -223,7 +231,7 @@ def get_recommendations(self):
@task(3)
def get_ads(self):
params = {
"productIds": [random.choice(products)],
"contextKeys": [random.choice(categories)],
}
self.client.get("/api/data/", params=params)

Expand Down