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

Commercetools Provider #774

Closed
wants to merge 1 commit into from
Closed
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
6 changes: 6 additions & 0 deletions packages/commercetools/.env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
COMMERCE_PROVIDER=@vercel/commerce-tools

COMMERCETOOLS_PROJECT_KEY=
COMMERCETOOLS_CLIENT_ID=
COMMERCETOOLS_CLIENT_SECRET=
COMMERCETOOLS_REGION=
2 changes: 2 additions & 0 deletions packages/commercetools/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dist
6 changes: 6 additions & 0 deletions packages/commercetools/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"useTabs": false
}
37 changes: 37 additions & 0 deletions packages/commercetools/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
## Commercetools Provider

**Demo:** https://saleor.vercel.store/

## Installation

1. Copy the `.env.template` file in this directory to `/site/.env.local` in the main directory
2. Set the environment following variables in your `.env.local`.

```
COMMERCE_PROVIDER=saleor
NEXT_PUBLIC_SALEOR_API_URL=https://vercel.saleor.cloud/graphql/
NEXT_PUBLIC_SALEOR_CHANNEL=default-channel
COMMERCE_IMAGE_HOST=vercel.saleor.cloud
```

3. Run `yarn` and then `yarn dev` in root folder

## Features:

```json
{
"provider": "commercetools",
"features": {
"wishlist": true,
"cart": true,
"search": true,
"customerAuth": true,
"customCheckout": false
}
}
```

## References

- API: https://docs.commercetools.com/api/
- SDK: https://docs.commercetools.com/sdk/javascript-sdk
84 changes: 84 additions & 0 deletions packages/commercetools/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
{
"name": "@vercel/commerce-commercetools",
"version": "0.0.1",
"license": "MIT",
"scripts": {
"release": "taskr release",
"build": "taskr build",
"dev": "taskr",
"types": "tsc --emitDeclarationOnly",
"prettier-fix": "prettier --write ."
},
"sideEffects": false,
"type": "module",
"exports": {
".": "./dist/index.js",
"./*": [
"./dist/*.js",
"./dist/*/index.js"
],
"./next.config": "./dist/next.config.cjs"
},
"typesVersions": {
"*": {
"*": [
"src/*",
"src/*/index"
],
"next.config": [
"dist/next.config.d.cts"
]
}
},
"files": [
"dist",
"schema.d.ts"
],
"publishConfig": {
"typesVersions": {
"*": {
"*": [
"dist/*.d.ts",
"dist/*/index.d.ts"
],
"next.config": [
"dist/next.config.d.cts"
]
}
}
},
"dependencies": {
"@commercetools/platform-sdk": "^2.8.0",
"@vercel/commerce": "^0.0.1",
"@vercel/fetch": "^6.1.1",
"lodash.debounce": "^4.0.8",
"swell-js": "^4.0.0-next.0"
},
"peerDependencies": {
"next": "^12",
"react": "^17",
"react-dom": "^17"
},
"devDependencies": {
"@taskr/clear": "^1.1.0",
"@taskr/esnext": "^1.1.0",
"@taskr/watch": "^1.1.0",
"@types/lodash.debounce": "^4.0.6",
"@types/node": "^17.0.8",
"@types/react": "^17.0.38",
"lint-staged": "^12.1.7",
"next": "^12.0.8",
"prettier": "^2.5.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"taskr": "^1.1.0",
"taskr-swc": "^0.0.1",
"typescript": "^4.5.4"
},
"lint-staged": {
"**/*.{js,jsx,ts,tsx,json}": [
"prettier --write",
"git add"
]
}
}
58 changes: 58 additions & 0 deletions packages/commercetools/src/api/endpoints/cart/add-item.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import {
getActiveCart,
normalizeCart,
removeCartCookie,
setCartId,
} from '../../../utils'
import type { CartEndpoint } from '.'
import { Cart, CartUpdate, ClientResponse } from '@commercetools/platform-sdk'

const addItem: CartEndpoint['handlers']['addItem'] = async ({
req,
res,
body: { item },
config,
}) => {
const activeCart = await getActiveCart(req, res, config.sdkFetch)
if (
(item.quantity &&
(!Number.isInteger(item.quantity) || item.quantity! < 1)) ||
!activeCart
) {
return res.status(400).json({
data: null,
errors: [{ message: 'Invalid request' }],
})
}
const lineItem: CartUpdate = {
version: activeCart.version,
actions: [
{
action: 'addLineItem',
variantId: +item.variantId,
productId: item.productId,
quantity: item.quantity ?? 1,
},
],
}
const updatedCart = await config.sdkFetch<ClientResponse<Cart>, CartUpdate>({
query: 'carts',
method: 'post',
variables: {
id: activeCart.id,
},
body: lineItem,
})

if (updatedCart.body) {
setCartId(res, updatedCart.body.id)
} else {
removeCartCookie(res)
}
const data = updatedCart.body
? normalizeCart(updatedCart.body, config)
: undefined
res.status(200).json({ data })
}

export default addItem
15 changes: 15 additions & 0 deletions packages/commercetools/src/api/endpoints/cart/get-cart.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { getActiveCart, normalizeCart } from '../../../utils'
import type { CartEndpoint } from '.'

// Return current cart info
const getCart: CartEndpoint['handlers']['getCart'] = async ({
req,
res,
config,
}) => {
const activeCart = await getActiveCart(req, res, config.sdkFetch)
const data = activeCart ? normalizeCart(activeCart, config) : undefined
res.status(200).json({ data })
}

export default getCart
26 changes: 26 additions & 0 deletions packages/commercetools/src/api/endpoints/cart/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { GetAPISchema, createEndpoint } from '@vercel/commerce/api'
import cartEndpoint from '@vercel/commerce/api/endpoints/cart'
import type { CartSchema } from '../../../types/cart'
import type { CommercetoolsAPI } from '../..'
import getCart from './get-cart'
import addItem from './add-item'
import updateItem from './update-item'
import removeItem from './remove-item'

export type CartAPI = GetAPISchema<CommercetoolsAPI, CartSchema>

export type CartEndpoint = CartAPI['endpoint']

export const handlers: CartEndpoint['handlers'] = {
getCart,
addItem,
updateItem,
removeItem,
}

const cartApi = createEndpoint<CartAPI>({
handler: cartEndpoint,
handlers,
})

export default cartApi
55 changes: 55 additions & 0 deletions packages/commercetools/src/api/endpoints/cart/remove-item.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import type { CartEndpoint } from '.'
import { COMMERCETOOLS_CART_COOKIE } from '../../../const'
import {
getActiveCart,
normalizeCart,
removeCartCookie,
setCartId,
} from '../../../utils'
import { Cart, CartUpdate, ClientResponse } from '@commercetools/platform-sdk'

const removeItem: CartEndpoint['handlers']['removeItem'] = async ({
res,
req,
body: { itemId },
config,
}) => {
const cartId = req.cookies[COMMERCETOOLS_CART_COOKIE]
const activeCart = await getActiveCart(req, res, config.sdkFetch)
if (!cartId || !itemId || !activeCart) {
return res.status(400).json({
data: null,
errors: [{ message: 'Invalid request' }],
})
}
const updatedCart = await config.sdkFetch<ClientResponse<Cart>, CartUpdate>({
query: 'carts',
method: 'post',
variables: {
id: activeCart.id,
},
body: {
version: activeCart.version,
actions: [
{
action: 'changeLineItemQuantity',
lineItemId: itemId,
quantity: 0,
},
],
},
})

if (updatedCart.body) {
setCartId(res, updatedCart.body.id)
} else {
removeCartCookie(res)
}

const data = updatedCart.body
? normalizeCart(updatedCart.body, config)
: undefined
res.status(200).json({ data })
}

export default removeItem
59 changes: 59 additions & 0 deletions packages/commercetools/src/api/endpoints/cart/update-item.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Cart, CartUpdate, ClientResponse } from '@commercetools/platform-sdk'
import {
getActiveCart,
normalizeCart,
removeCartCookie,
setCartId,
} from '../../../utils'
import type { CartEndpoint } from '.'

const updateItem: CartEndpoint['handlers']['updateItem'] = async ({
req,
res,
body: { itemId, item },
config,
}) => {
const activeCart = await getActiveCart(req, res, config.sdkFetch)
if (!itemId || !item || !activeCart) {
return res.status(400).json({
data: null,
errors: [{ message: 'Invalid request' }],
})
}

const lineItem: CartUpdate = {
version: activeCart.version,
actions: [
{
action: 'changeLineItemQuantity',
lineItemId: activeCart.lineItems.find(
(lineItem) =>
lineItem.productId === item.productId &&
`${lineItem.variant.id}` === item.variantId
)!.id,
quantity: item.quantity!,
},
],
}
const updatedCart = await config.sdkFetch<ClientResponse<Cart>, CartUpdate>({
query: 'carts',
method: 'post',
variables: {
id: activeCart.id,
},
body: lineItem,
})

if (updatedCart.body) {
setCartId(res, updatedCart.body.id)
} else {
removeCartCookie(res)
}

const data = updatedCart.body
? normalizeCart(updatedCart.body, config)
: undefined
res.status(200).json({ data })
}

export default updateItem
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { ProductsEndpoint } from '.'
import {
ClientResponse,
ProductProjectionPagedQueryResponse,
} from '@commercetools/platform-sdk'
import { getSortVariables, normalizeProduct } from '../../../../utils'

const getProducts: ProductsEndpoint['handlers']['getProducts'] = async ({
res,
body,
config,
}) => {
const { search, categoryId, sort } = body
const response = await config.sdkFetch<
ClientResponse<ProductProjectionPagedQueryResponse>
>({
query: 'productProjections',
method: 'get',
variables: {
expand: ['masterData.current'],
sort: getSortVariables(sort),
...(search ? { search: { [`text.${config.locale!}`]: search } } : {}),
...(categoryId
? { filters: `categories.id: subtree("${categoryId}")` }
: {}),
},
})

const data = {
products: response.body.results.map((product) =>
normalizeProduct(product, config)
),
found: response.body.count > 0,
}
res.status(200).json({ data })
}

export default getProducts
Loading