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

Feat: example Dynamic Content #426

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
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: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# starter.store

A starter powered by FastStore.
A starter powered by FastStore .
83 changes: 83 additions & 0 deletions cms/faststore/sections.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
[
{
"name": "FixedImageHero",
"schema": {
"title": "Hero with a Fixed Image",
"description": "Add a quick promotion with an image/action pair",
"type": "object",
"required": ["title"],
"properties": {
"title": {
"title": "Title",
"type": "string"
},
"subtitle": {
"title": "Subtitle",
"type": "string"
},
"link": {
"title": "Call to Action",
"type": "object",
"properties": {
"text": {
"type": "string",
"title": "Text"
},
"url": {
"type": "string",
"title": "URL"
},
"linkTargetBlank": {
"type": "boolean",
"title": "Open link in new window?",
"default": false
}
}
},
"colorVariant": {
"type": "string",
"title": "Color variant",
"enumNames": ["Main", "Light", "Accent"],
"enum": ["main", "light", "accent"]
},
"variant": {
"type": "string",
"title": "Variant",
"enumNames": ["Primary", "Secondary"],
"enum": ["primary", "secondary"]
}
}
}
},
{
"name": "CallToAction",
"requiredScopes": [],
"schema": {
"title": "Call To Action",
"description": "Get your 20% off on the first purchase!",
"type": "object",
"required": ["title", "link"],
"properties": {
"title": {
"title": "Title",
"type": "string"
},
"link": {
"title": "Link Path",
"type": "object",
"required": ["text", "url"],
"properties": {
"text": {
"title": "Text",
"type": "string"
},
"url": {
"title": "URL",
"type": "string"
}
}
}
}
}
}
]
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@
"test": "faststore test"
},
"dependencies": {
"@faststore/core": "3.0.35",
"@faststore/core": "https://pkg.csb.dev/vtex/faststore/commit/96f11239/@faststore/core",
"next": "^13.5.6",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@cypress/code-coverage": "^3.12.1",
"@faststore/cli": "3.0.35",
"@faststore/cli": "https://pkg.csb.dev/vtex/faststore/commit/96f11239/@faststore/cli",
"@faststore/lighthouse": "^3.0.7",
"@lhci/cli": "^0.9.0",
"@testing-library/cypress": "^10.0.1",
Expand Down
4 changes: 4 additions & 0 deletions src/components/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import CallToAction from "./sections/CallToAction";
import FixedImageHero from "./sections/FixedImageHero";

export default { CallToAction, FixedImageHero };
21 changes: 21 additions & 0 deletions src/components/sections/CallToAction.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useDynamicContent } from "@faststore/core";
import { ServerDynamicContentQuery } from "@faststore/core/api";

export interface CallToActionProps {
title: string;
link: {
text: string;
url: string;
};
}

export default function CallToAction(props: CallToActionProps) {
const context = useDynamicContent<ServerDynamicContentQuery>();
console.log("🚀 ~ CallToAction context:", context);
return (
<section>
<h2>{`${props.title} ${context?.data?.namedExtraData?.data}`}</h2>
<pre>{`${JSON.stringify(context?.data, null, 2)}`}</pre>
</section>
);
}
45 changes: 45 additions & 0 deletions src/components/sections/FixedImageHero.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import {
HeroSection,
getOverriddenSection,
useDynamicContent,
} from "@faststore/core";
import { ServerDynamicContentQuery } from "@faststore/core/api";

const OverridenHero = getOverriddenSection({
Section: HeroSection,
components: {
HeroImage: {
Component: CustomHeroImage,
},
},
});

function CustomHeroImage() {
const context = useDynamicContent<ServerDynamicContentQuery>();
console.log("🚀 ~ CustomHeroImage context:", context);

return (
<img
src={
context.data?.extraData?.customFieldFromRoot ??
"https://via.placeholder.com/350"
}
width={400}
alt={context.data?.extraData?.customField ?? "Hero section image"}
/>
);
}

export default function FixedImageHero(
props: React.ComponentProps<typeof OverridenHero>
) {
const context = useDynamicContent<ServerDynamicContentQuery>();
console.log("🚀 ~ FixedImageHero context:", context);
return (
<OverridenHero
{...props}
image={{ src: "noop", alt: "noop" }}
title={context.data?.extraData?.customField ?? "Hero section title"}
/>
);
}
101 changes: 101 additions & 0 deletions src/dynamicContent/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// starter.store code that will be copied to .faststore (core)

import {
ServerDynamicContentQuery,
ServerDynamicContentQueryVariables,
gql,
} from "@faststore/core/api";
import { execute_unstable as execute } from "@faststore/core/experimental";
eduardoformiga marked this conversation as resolved.
Show resolved Hide resolved

async function fetchDataMyLandingPage() {
const response = await fetch("https://fakestoreapi.com/products/1");
const data = await response.json();
return {
data,
};
}

async function fetchDataOtherLandingPage() {
const response = await fetch("other-api/other-landing-page-endpoint");
const data = await response.json();
return {
data,
};
}

async function fetchDataUsingPromiseAll() {
try {
const [apiData1, apiData2] = await Promise.all([
fetch("my-api/endpoint-1").then((response) => response.json()),
fetch("my-api/endpoint-2").then((response) => response.json()),
]);

return {
data: {
apiData1,
apiData2,
},
};
} catch (error) {
console.error("Error fetching data from APIs:", error);
return {
data: null,
errors: ["Error fetching data from APIs"],
};
}
}

const query = gql(`
query ServerDynamicContent($name: String!){
extraData {
data {
title
rating {
rate
count
}
}
customField
customFieldFromRoot
}
namedExtraData(name: $name) {
data
}
}
`);

async function fetchDataUsingApiExtension() {
try {
const dynamicContentResult = await execute<
ServerDynamicContentQueryVariables,
ServerDynamicContentQuery
>({
variables: {
name: "Variables passed to query - Dynamic Content Feature",
},
operation: query,
});
return {
data: dynamicContentResult.data,
};
} catch (error) {
console.error("Error fetching data from APIs:", error);
return {
data: null,
errors: ["Error fetching data from APIs"],
};
}
}

// map the slug to correspondent functions
const dynamicContent = {
home: fetchDataUsingApiExtension,
"my-landing-page": fetchDataUsingApiExtension,
// "my-landing-page": fetchDataMyLandingPage,
"other-landing-page": fetchDataOtherLandingPage,
"landing-page-using-promise-all": fetchDataUsingPromiseAll,
"landing-page-using-api-extension": fetchDataUsingApiExtension,
about: fetchDataUsingApiExtension,
};

export default dynamicContent;
13 changes: 13 additions & 0 deletions src/graphql/thirdParty/resolvers/extraData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { ExtraDataRoot } from "./query";

export const ExtraData = {
data: (root: ExtraDataRoot) => root.data,
customFieldFromRoot: (root: ExtraDataRoot) => root?.data?.[0]?.image ?? "",
customField: async (_: ExtraDataRoot) => {
const res = await fetch(
"https://fakestoreapi.com/products/category/jewelery"
);
const customField = await res.json();
return (customField?.[0]?.title as string) ?? "";
},
};
9 changes: 9 additions & 0 deletions src/graphql/thirdParty/resolvers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ExtraData } from "./extraData";
import { Query } from "./query";

const resolvers = {
ExtraData,
Query,
};

export default resolvers;
37 changes: 37 additions & 0 deletions src/graphql/thirdParty/resolvers/query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
export type ProductsExtraData = {
id: number;
title: string;
price: number;
description: string;
category: string;
image: string;
rating: {
rate: string;
count: number;
};
};

export type ExtraDataRoot = {
data?: ProductsExtraData[];
};

async function getProductsFromThirdPartyApi() {
const result = await fetch("https://fakestoreapi.com/products");
const json = result.json();
return json;
}

export const Query = {
extraData: async (): Promise<{ data: ProductsExtraData[] }> => {
const products: ProductsExtraData[] = await getProductsFromThirdPartyApi();

return {
data: products,
};
},
namedExtraData: (_: unknown, { name }: { name: string }) => {
return {
data: `Named extra data: ${name}`,
};
},
};
35 changes: 35 additions & 0 deletions src/graphql/thirdParty/typeDefs/extra.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
type Rating {
rate: String
count: Int
}

type ProductsExtraData {
id: Int
title: String
price: Float
description: String
category: String
image: String
rating: Rating
}

type ExtraData {
"""
Data customizing ExtraData
"""
data: [ProductsExtraData]
customFieldFromRoot: String
customField: String
}

type NamedExtraData {
"""
Data customizing NamedExtraData
"""
data: String!
}

type Query {
extraData: ExtraData
namedExtraData(name: String!): NamedExtraData
}
Loading