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

Add edge function #4

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ public
src/gatsby-types.d.ts
.env.*
!.env.example
.netlify
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports.rome": true
}
},
"deno.enablePaths": ["netlify/edge-functions"]
}
2 changes: 2 additions & 0 deletions netlify.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
publish="public"
80 changes: 80 additions & 0 deletions netlify/edge-functions/experiment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Context } from "https://edge.netlify.com";
import { HTMLRewriter } from "https://raw.githubusercontent.com/worker-tools/html-rewriter/master/index.ts";

type Experiment = {
slug: string;
};

type CampaignsConfig = {
campaigns: { id: string; trafficAmount: number; experiments: Experiment[] }[];
};
export default async (request: Request, context: Context) => {
const next = await context.next();
let config: CampaignsConfig = { campaigns: [] };
let buffer = "";

Array(10)
.fill()
.map((_, index) => {
const name = `edge-campaign-${index}`;
console.log({ name });
const isSet = context.cookies.get(name);

console.log({ index, isSet });

if (!isSet) {
context.cookies.set({
name,
value: Math.random(),
});
}
});

return new HTMLRewriter()
.on("#edge-config", {
text(scriptText) {
buffer += scriptText.text;
if (scriptText.lastInTextNode) {
config = JSON.parse(buffer);
}
},
})
.on("body", {
element(bodyEl) {
try {
const experimentSlugs = config?.campaigns
?.filter(({ id, trafficAmount }, index) => {
const name = `edge-campaign-${index}`;
const probability = parseFloat(context.cookies.get(name));

console.log({ probability });

const isOn = probability > trafficAmount / 100;

console.log("BUCKET", isOn);

return isOn;
})
.map((campaign) => {
return campaign.experiments.map(
({ slug }) => `edge-experiment-${slug}`
);
})
.flat()
.join(" ");

console.log({ experimentSlugs });

bodyEl.setAttribute("class", experimentSlugs);

console.log("EDGE CONFIG", JSON.stringify(config, null, 2));
} catch (error) {
console.log("ERROR");
console.log(error);
}
},
})
.transform(next);
};

export const config = { path: "/" };
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@commercelayer/js-auth": "4.0.0",
"@commercelayer/react-components": "^4.4.4",
"@frontegg/react": "^5.0.44",
"classnames": "^2.3.2",
"gatsby": "^5.9.0",
"gatsby-plugin-image": "^3.11.0",
"gatsby-plugin-manifest": "^5.9.0",
Expand Down
12 changes: 12 additions & 0 deletions src/components/Card/src/Card.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,15 @@
.footer {
padding: 20px;
}

:global(.edge-experiment-list-no-cards .product-section) {
.card {
flex-direction: row;
justify-content: space-between;
}

.image,
.imageWrapper {
display: none;
}
}
6 changes: 4 additions & 2 deletions src/components/Card/src/Card.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import { GatsbyImage, IGatsbyImageData } from "gatsby-plugin-image";
import { cloneElement, isValidElement, useMemo } from "react";
import classnames from "classnames";
import * as styles from "./Card.module.scss";

export type CardProps = {
title: React.ReactNode;
children: React.ReactNode;
imageData?: IGatsbyImageData;
footer?: React.ReactNode;
className?: string;
};

const Card = ({ title, children, imageData, footer }: CardProps) => {
const Card = ({ title, children, imageData, footer, className }: CardProps) => {
return (
<div className={styles.card}>
<div className={classnames(styles.card, className)}>
{imageData && (
<div className={styles.imageWrapper}>
<GatsbyImage
Expand Down
6 changes: 6 additions & 0 deletions src/components/Hero/src/Hero.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,9 @@
transform: translateY(-50%);
z-index: 1;
}

:global(.edge-experiment-grey-bkg) {
.hero {
background: grey;
}
}
21 changes: 21 additions & 0 deletions src/components/ProductSection/src/ProductSection.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
.cardContent {
display: flex;
justify-content: space-between;
align-items: center;
}

.cardWrapper {
display: flex;
gap: 10px;
margin-top: 50px;
}

:global(.edge-experiment-list-no-cards) {
.cardWrapper {
flex-direction: column;
}

.cardContent {
flex-direction: row;
}
}
14 changes: 5 additions & 9 deletions src/components/ProductSection/src/ProductSection.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Price, PricesContainer } from "@commercelayer/react-components";
import { graphql, Link } from "gatsby";
import ReactMarkdown from "react-markdown";
import classnames from "classnames";
import * as styles from "./ProductSection.module.scss";
import Card from "../../Card";

const ProductSection = ({ data }: { data: Queries.ProductSectionFragment }) => {
Expand All @@ -9,14 +11,14 @@ const ProductSection = ({ data }: { data: Queries.ProductSectionFragment }) => {
}

return (
<div>
<div className={classnames(styles.productSection, "product-section")}>
<h2>{data.title}</h2>
{data.description?.description && (
<div>
<ReactMarkdown>{data.description.description}</ReactMarkdown>
</div>
)}
<div style={{ display: "flex", gap: 10, marginTop: 50 }}>
<div className={styles.cardWrapper}>
{data.products.map((product) => {
if (!product) {
return null;
Expand All @@ -35,13 +37,7 @@ const ProductSection = ({ data }: { data: Queries.ProductSectionFragment }) => {
imageData={image?.gatsbyImageData || undefined}
footer={<Link to={slug}>Catch it!</Link>}
>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<div className={styles.cardContent}>
{shortDescription?.shortDescription && (
<p>{shortDescription?.shortDescription}</p>
)}
Expand Down
14 changes: 14 additions & 0 deletions src/components/Sections/src/Sections.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,17 @@
padding-top: 50px;
border-top: 1px solid #ccc;
}

.b {
display: none;
}

:global(.edge-experiment-invert-order-homepage) {
.a {
display: none;
}

.b {
display: block;
}
}
71 changes: 67 additions & 4 deletions src/components/Sections/src/Sections.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,68 @@ import ProductSection from "../../ProductSection";
import TitleWithContent from "../../TitleWithContent";
import * as styles from "./Sections.module.scss";

const typenameToSectionComponentMap = {
const typenameToSectionComponentMapExperiment = {
ContentfulProductSection: ProductSection,
ContentfulTitleWithContent: TitleWithContent,
};

const ExperimentSection = ({ data }: { data: Queries.SectionsFragment }) => {
if (!data.a || !data.b) {
return null;
}

return (
<>
<div className={styles.a}>
{data.a.map((section) => {
if (!section) {
return null;
}

const Component =
typenameToSectionComponentMapExperiment[section.__typename];

if (!Component) {
return null;
}

return (
<div className={styles.section}>
{/* @ts-ignore No idea why an error here either. */}
<Component data={section} />
</div>
);
})}
</div>
<div className={styles.b}>
{data.b.map((section) => {
if (!section) {
return null;
}

const Component =
typenameToSectionComponentMapExperiment[section.__typename];

if (!Component) {
return null;
}

return (
<div className={styles.section}>
{/* @ts-ignore No idea why an error here either. */}
<Component data={section} />
</div>
);
})}
</div>
</>
);
};

const typenameToSectionComponentMap = {
ContentfulExperimentReferences: ExperimentSection,
};

// @todo: this should be changed to Sections fragment. Not sure why isn't working yet.
const Sections = ({ data }: { data: readonly Queries.SectionsFragment[] }) => {
return (
Expand All @@ -34,9 +91,15 @@ export default Sections;

export const query = graphql`
# Fragment type should be changed to custom union.
fragment Sections on ContentfulProductSectionContentfulTitleWithContentUnion {
fragment Sections on ContentfulExperimentReferences {
__typename
...ProductSection
...TitleWithContent
a {
...ProductSection
...TitleWithContent
}
b {
...ProductSection
...TitleWithContent
}
}
`;
26 changes: 25 additions & 1 deletion src/templates/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,17 @@ const IndexPage = ({ data }: PageProps<Queries.PageQuery>) => {

export default IndexPage;

export const Head: HeadFC = () => <title>Home Page</title>;
export const Head: HeadFC<Queries.PageQuery> = ({ data }) => (
<>
<title>Home Page</title>
{/* @ts-ignore */}
<script id="edge-config" language="json">
{JSON.stringify({
campaigns: data.allContentfulCampaign.nodes,
})}
</script>
</>
);

export const query = graphql`
query Page($slug: String!) {
Expand All @@ -40,5 +50,19 @@ export const query = graphql`
...Sections
}
}
allContentfulCampaign {
nodes {
id
trafficAmount
experiments {
... on ContentfulExperiment {
slug
}
... on ContentfulExperimentReferences {
slug
}
}
}
}
}
`;
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3758,7 +3758,7 @@ [email protected], ci-info@^2.0.0:
resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-2.0.0.tgz#67a9e964be31a51e15e5010d58e6f12834002f46"
integrity sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==

classnames@^2.3.1:
classnames@^2.3.1, classnames@^2.3.2:
version "2.3.2"
resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.3.2.tgz#351d813bf0137fcc6a76a16b88208d2560a0d924"
integrity sha512-CSbhY4cFEJRe6/GQzIk5qXZ4Jeg5pcsP7b5peFSDpffpe1cqjASH/n9UTjBwOp6XpMSTwQ8Za2K5V02ueA7Tmw==
Expand Down