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

Feature/commerce example #145

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
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
3 changes: 3 additions & 0 deletions examples/commerce/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
36 changes: 36 additions & 0 deletions examples/commerce/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
36 changes: 36 additions & 0 deletions examples/commerce/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
123 changes: 123 additions & 0 deletions examples/commerce/app/api/cart/[cartId]/lines/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { carts } from "db/carts";
import { products } from "db/products";
import { Cart, CartItem, Product } from "lib/shopify/types";

type Params = {
cartId: string;
};

export async function POST(request: Request, context: { params: Params }) {
await new Promise((resolve) => setTimeout(resolve, 300));
const cart = carts.get(context.params.cartId);

if (!cart) {
return new Response(JSON.stringify({ error: "Cart not found" }), { status: 404 });
}

const { lines } = (await request.json()) as {
lines: { merchandiseId: string; quantity: number }[];
};

for (const line of lines) {
const product = products.find(p => p.variants.some(v => v.id === line.merchandiseId));
const variant = product?.variants.find(v => v.id === line.merchandiseId);

if (!product || !variant) {
return new Response(JSON.stringify({ error: "Product or variant not found" }), { status: 404 });
}

const newItem: CartItem = {
id: Math.random().toString(36).substr(2, 9),
quantity: line.quantity,
cost: {
totalAmount: {
amount: (parseFloat(variant.price.amount) * line.quantity).toFixed(2),
currencyCode: variant.price.currencyCode,
},
},
merchandise: {
id: variant.id,
title: variant.title,
selectedOptions: variant.selectedOptions,
product: product,
},
};

cart.lines.push(newItem);
}

// updateCartTotals(cart);

return Response.json(cart);
}

function updateCartTotals(cart: Cart) {
let subtotal = 0;
let totalQuantity = 0;

for (const line of cart.lines) {
subtotal += parseFloat(line.cost.totalAmount.amount);
totalQuantity += line.quantity;
}

const taxRate = 0.1;
const tax = subtotal * taxRate;
const total = subtotal + tax;

cart.cost = {
subtotalAmount: {
amount: subtotal.toFixed(2),
currencyCode: "USD",
},
totalAmount: {
amount: total.toFixed(2),
currencyCode: "USD",
},
totalTaxAmount: {
amount: tax.toFixed(2),
currencyCode: "USD",
},
};
cart.totalQuantity = totalQuantity;
}

export async function DELETE(request: Request, context: { params: Params }) {
await new Promise((resolve) => setTimeout(resolve, 300));
const cart = carts.get(context.params.cartId);

if (!cart) {
return new Response(JSON.stringify({ error: "Cart not found" }), { status: 404 });
}

const { lineIds } = (await request.json()) as { lineIds: string[] };

cart.lines = cart.lines.filter((line) => !lineIds.includes(line.id));

return Response.json(carts.get(context.params.cartId));
}

export async function PUT(request: Request, context: { params: Params }) {
await new Promise((resolve) => setTimeout(resolve, 300));
const cart = carts.get(context.params.cartId);

if (!cart) {
return new Response(JSON.stringify({ error: "Cart not found" }), { status: 404 });
}

const { lines } = (await request.json()) as {
lines: { id: string; merchandiseId: string; quantity: number }[];
};

cart.lines = cart.lines.map((line) => {
const updatedLine = lines.find((l) => l.id === line.id);

if (updatedLine) {
line.merchandise.id = updatedLine.merchandiseId;
line.quantity = updatedLine.quantity;
}

return line;
});

return Response.json(carts.get(context.params.cartId));
}
10 changes: 10 additions & 0 deletions examples/commerce/app/api/cart/[cartId]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { carts } from "db/carts";

type Params = {
cartId: string;
};

export async function GET(_: Request, context: { params: Params }) {
await new Promise((resolve) => setTimeout(resolve, 300));
return Response.json(carts.get(context.params.cartId));
}
30 changes: 30 additions & 0 deletions examples/commerce/app/api/cart/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { carts } from "db/carts";
import { Cart } from "lib/shopify/types";

const generateId = () => Math.random().toString(36).substr(2, 9);

export async function POST(request: Request) {
const cart = {
id: generateId(),
checkoutUrl: "http://localhost:3000/api/checkout",
lines: [],
cost: {
subtotalAmount: {
amount: "0.00",
currencyCode: "USD",
},
totalAmount: {
amount: "0.00",
currencyCode: "USD",
},
totalTaxAmount: {
amount: "0.00",
currencyCode: "USD",
},
},
totalQuantity: 0,
};

carts.set(request.headers.get("cartId") || "", cart);
return cart;
}
10 changes: 10 additions & 0 deletions examples/commerce/app/api/collections/[handle]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { collections } from "db/collections";

type Params = {
handle: string;
};

export async function GET(request: Request, context: { params: Params }) {
await new Promise((resolve) => setTimeout(resolve, 500));
return Response.json(collections.find(collection => collection.handle === context.params.handle));
}
129 changes: 129 additions & 0 deletions examples/commerce/app/api/collections/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { Collection } from "lib/shopify/types";

export async function GET(request: Request) {
await new Promise((resolve) => setTimeout(resolve, 500));

return Response.json([{
handle: '',
title: 'All',
description: 'All products',
seo: {
title: 'All',
description: 'All products'
},
path: '/search',
updatedAt: new Date().toISOString()
}, {
handle: "bags",
title: "Bags",
description: "All bags",
seo: {
title: "Bags",
description: "All bags"
},
path: "/search/bags",
updatedAt: new Date().toISOString()
},
{
handle: "drinkware",
title: "Drinkware",
description: "All drinkware",
seo: {
title: "Drinkware",
description: "All drinkware"
},
path: "/search/drinkware",
updatedAt: new Date().toISOString()
}, {
handle: "electronics",
title: "Electronics",
description: "All electronics",
seo: {
title: "Electronics",
description: "All electronics"
},
path: "/search/electronics",
updatedAt: new Date().toISOString()
}, {
handle: "footware",
title: "Footware",
description: "All footware",
seo: {
title: "Footware",
description: "All footware"
},
path: "/search/footware",
updatedAt: new Date().toISOString()
}, {
handle: "headwear",
title: "Headwear",
description: "All headwear",
seo: {
title: "Headwear",
description: "All headwear"
},
path: "/search/headwear",
updatedAt: new Date().toISOString()
}, {
handle: "hoodies",
title: "Hoodies",
description: "All hoodies",
seo: {
title: "Hoodies",
description: "All hoodies"
},
path: "/search/hoodies",
updatedAt: new Date().toISOString()
}, {
handle: "jackets",
title: "Jackets",
description: "All jackets",
seo: {
title: "Jackets",
description: "All jackets"
},
path: "/search/jackets",
updatedAt: new Date().toISOString()
}, {
handle: "kids",
title: "Kids",
description: "All kids",
seo: {
title: "Kids",
description: "All kids"
},
path: "/search/kids",
updatedAt: new Date().toISOString()
}, {
handle: "pets",
title: "Pets",
description: "All pets",
seo: {
title: "Pets",
description: "All pets"
},
path: "/search/pets",
updatedAt: new Date().toISOString()
}, {
handle: "shirts",
title: "Shirts",
description: "All shirts",
seo: {
title: "Shirts",
description: "All shirts"
},
path: "/search/shirts",
updatedAt: new Date().toISOString()
}, {
handle: "stickers",
title: "Stickers",
description: "All stickers",
seo: {
title: "Stickers",
description: "All stickers"
},
path: "/search/stickers",
updatedAt: new Date().toISOString()
}
] satisfies Collection[]);
}
Loading