ce-storefront
v0.22.10
Published
<!-- Start Summary [summary] --> ## Summary
Readme
ce-storefront
Summary
CE Storefront APIs: Customer-facing e-commerce API for building exceptional shopping experiences
Public-facing API for Commerce Engine storefronts, enabling seamless shopping experiences with product browsing, cart management, checkout processing, user accounts, and order tracking. Perfect for building web, mobile, and headless commerce applications.
For more information about the API: Commerce Engine API Reference Documentation
Table of Contents
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add ce-storefrontPNPM
pnpm add ce-storefrontBun
bun add ce-storefrontYarn
yarn add ce-storefront[!NOTE] This package is published as an ES Module (ESM) only. For applications using CommonJS, use
await import("ce-storefront")to import and use this package.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { CeStorefront } from "ce-storefront";
const ceStorefront = new CeStorefront();
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "<YOUR_API_KEY_HERE>",
});
console.log(result);
}
run();
Available Resources and Operations
Auth
- getAnonymousToken - Anonymous user
- generateOtp - Generate OTP
- loginWithEmail - Login with email
- loginWithPhone - Login with phone
- loginWithWhatsapp - Login with whatsapp
- logout - Logout user
- refreshToken - Refresh access token
- getUserDetail - Retrieve a user
- updateUser - Update a user
- verifyOtp - Verify OTP
Carts
- createCart - Create cart
- fulfillmentOptions - Retrieve fulfillment options
- getUserCart - Retrieve cart using user id
- removeUserCart - Delete cart using user id
- getCart - Retrieve cart detail
- deleteCart - Delete cart
- createCartAddress - Update cart address
- applyCoupon - Apply coupon
- removeCoupon - Remove coupon
- updateFulfillmentPreference - Update fulfillment preference
- updateCart - Add/delete cart item
- redeemLoyaltyPoints - Redeem loyalty points
- removeLoyaltyPoints - Remove loyalty points
- checkFulfillment - Check fulfillment
Catalog
- listCategories - List all categories
- listProducts - List all products
- listCrosssellProducts - Retrieve cross-sell products
- searchProducts - Search products
- listSimilarProducts - Retrieve similar products
- listUpsellProducts - Retrieve up-sell products
- getProductDetail - Retrieve a product detail
- listProductReviews - List all product reviews
- listProductVariants - Retrieve product variants
- getVariantDetail - Retrieve variant detail
- listSkus - List all SKUs
Common
- listCountryPincodes - Retrieve pincodes
Customers
- listCustomerCards - List all saved cards
- listSavedPaymentMethods - List all saved payment methods
- listAddresses - Retrieve all addresses
- createAddress - Create address
- getAddressDetail - Retrieve particular address
- updateAddressDetail - Update particular address
- deleteAddress - Remove particular address
- getLoyaltyDetails - Retrieve loyalty details
- listUserReviews - Retrieve all reviews
Marketplace
- listCategories - List all categories
- listProducts - List all products
- listCrosssellProducts - Retrieve cross-sell products
- searchProducts - Search products
- listSimilarProducts - Retrieve similar products
- listUpsellProducts - Retrieve up-sell products
- getProductDetail - Retrieve a product detail
- listProductReviews - List all product reviews
- listProductVariants - Retrieve product variants
- getVariantDetail - Retrieve variant detail
- listSkus - List all SKUs
Orders
- createOrder - Create order
- listOrders - Retrieve all orders
- getOrderDetail - Retrieve order detail
- cancelOrder - Cancel order
- getPaymentStatus - Retrieve payment status
- retryOrderPayment - Retry payment
- listOrderShipments - Retrieve order shipments
Payments
- getCardInfo - Get card information
Store
- getSellerDetail - Retrieve seller detail
- listSellerReviews - List seller reviews
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
authGenerateOtp- Generate OTPauthGetAnonymousToken- Anonymous userauthGetUserDetail- Retrieve a userauthLoginWithEmail- Login with emailauthLoginWithPhone- Login with phoneauthLoginWithWhatsapp- Login with whatsappauthLogout- Logout userauthRefreshToken- Refresh access tokenauthUpdateUser- Update a userauthVerifyOtp- Verify OTPcartsApplyCoupon- Apply couponcartsCheckFulfillment- Check fulfillmentcartsCreateCart- Create cartcartsCreateCartAddress- Update cart addresscartsDeleteCart- Delete cartcartsFulfillmentOptions- Retrieve fulfillment optionscartsGetCart- Retrieve cart detailcartsGetUserCart- Retrieve cart using user idcartsRedeemLoyaltyPoints- Redeem loyalty pointscartsRemoveCoupon- Remove couponcartsRemoveLoyaltyPoints- Remove loyalty pointscartsRemoveUserCart- Delete cart using user idcartsUpdateCart- Add/delete cart itemcartsUpdateFulfillmentPreference- Update fulfillment preferencecatalogGetProductDetail- Retrieve a product detailcatalogGetVariantDetail- Retrieve variant detailcatalogListCategories- List all categoriescatalogListCrosssellProducts- Retrieve cross-sell productscatalogListProductReviews- List all product reviewscatalogListProducts- List all productscatalogListProductVariants- Retrieve product variantscatalogListSimilarProducts- Retrieve similar productscatalogListSkus- List all SKUscatalogListUpsellProducts- Retrieve up-sell productscatalogSearchProducts- Search productscommonListCountryPincodes- Retrieve pincodescustomersCreateAddress- Create addresscustomersDeleteAddress- Remove particular addresscustomersGetAddressDetail- Retrieve particular addresscustomersGetLoyaltyDetails- Retrieve loyalty detailscustomersListAddresses- Retrieve all addressescustomersListCustomerCards- List all saved cardscustomersListSavedPaymentMethods- List all saved payment methodscustomersListUserReviews- Retrieve all reviewscustomersUpdateAddressDetail- Update particular addressmarketplaceGetProductDetail- Retrieve a product detailmarketplaceGetVariantDetail- Retrieve variant detailmarketplaceListCategories- List all categoriesmarketplaceListCrosssellProducts- Retrieve cross-sell productsmarketplaceListProductReviews- List all product reviewsmarketplaceListProducts- List all productsmarketplaceListProductVariants- Retrieve product variantsmarketplaceListSimilarProducts- Retrieve similar productsmarketplaceListSkus- List all SKUsmarketplaceListUpsellProducts- Retrieve up-sell productsmarketplaceSearchProducts- Search productsordersCancelOrder- Cancel orderordersCreateOrder- Create orderordersGetOrderDetail- Retrieve order detailordersGetPaymentStatus- Retrieve payment statusordersListOrders- Retrieve all ordersordersListOrderShipments- Retrieve order shipmentsordersRetryOrderPayment- Retry paymentpaymentsGetCardInfo- Get card informationstoreGetSellerDetail- Retrieve seller detailstoreListSellerReviews- List seller reviews
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { CeStorefront } from "ce-storefront";
const ceStorefront = new CeStorefront();
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "<YOUR_API_KEY_HERE>",
}, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { CeStorefront } from "ce-storefront";
const ceStorefront = new CeStorefront({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "<YOUR_API_KEY_HERE>",
});
console.log(result);
}
run();
Error Handling
CeStorefrontError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | --------------------------------------------------------------------------------------- |
| error.message | string | Error message |
| error.statusCode | number | HTTP response status code eg 404 |
| error.headers | Headers | HTTP response headers |
| error.body | string | HTTP body. Can be empty string if no body is returned. |
| error.rawResponse | Response | Raw HTTP response |
| error.data$ | | Optional. Some errors may contain structured data. See Error Classes. |
Example
import { CeStorefront } from "ce-storefront";
import * as errors from "ce-storefront/models/errors";
const ceStorefront = new CeStorefront();
async function run() {
try {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "<YOUR_API_KEY_HERE>",
});
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.CeStorefrontError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.BadRequest) {
console.log(error.data$.message); // string
console.log(error.data$.success); // boolean
console.log(error.data$.code); // string
console.log(error.data$.error); // errors.ErrorT
}
}
}
}
run();
Error Classes
Primary errors:
CeStorefrontError: The base class for HTTP error responses.Unauthorized: Not authorized for given operation on the Resource. Status code401. *NotFound: Requested resource not found. Status code404. *
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from CeStorefrontError:
BadRequest: Bad request. Status code400. Applicable to 32 of 66 methods.*ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
Server Selection
Select Server by Name
You can override the default server globally by passing a server name to the server: keyof typeof ServerList optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:
| Name | Server | Variables | Description |
| --------- | ------------------------------------------------------------------- | ---------- | -------------- |
| staging | https://staging.api.commercengine.io/api/v1/{store_id}/storefront | store_id | Staging Server |
| prod | https://prod.api.commercengine.io/api/v1/{store_id}/storefront | store_id | Prod Server |
If the selected server has variables, you may override its default values through the additional parameters made available in the SDK constructor:
| Variable | Parameter | Default | Description |
| ---------- | ----------------- | ------------ | ----------- |
| store_id | storeId: string | "store_id" | Store ID |
Example
import { CeStorefront } from "ce-storefront";
const ceStorefront = new CeStorefront({
server: "staging",
storeId: "store_id",
});
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "<YOUR_API_KEY_HERE>",
});
console.log(result);
}
run();
Override Server URL Per-Client
The default server can also be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { CeStorefront } from "ce-storefront";
const ceStorefront = new CeStorefront({
serverURL: "https://staging.api.commercengine.io/api/v1/store_id/storefront",
});
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "<YOUR_API_KEY_HERE>",
});
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to use the "beforeRequest" hook to to add a
custom header and a timeout to requests and how to use the "requestError" hook
to log errors:
import { CeStorefront } from "ce-storefront";
import { HTTPClient } from "ce-storefront/lib/http";
const httpClient = new HTTPClient({
// fetcher takes a function that has the same signature as native `fetch`.
fetcher: (request) => {
return fetch(request);
}
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new CeStorefront({ httpClient: httpClient });Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
| --------------- | ---- | ----------- |
| authorization | http | HTTP Bearer |
To authenticate with the API the authorization parameter must be set when initializing the SDK client instance. For example:
import { CeStorefront } from "ce-storefront";
const ceStorefront = new CeStorefront({
authorization: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await ceStorefront.auth.generateOtp({
requestBody: {
channel: "email",
email: "[email protected]",
otpAction: "verify-email",
},
});
console.log(result);
}
run();
Per-Operation Security Schemes
Some operations in this SDK require the security scheme to be specified at the request level. For example:
import { CeStorefront } from "ce-storefront";
const ceStorefront = new CeStorefront();
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "<YOUR_API_KEY_HERE>",
});
console.log(result);
}
run();
Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { CeStorefront } from "ce-storefront";
const sdk = new CeStorefront({ debugLogger: console });Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
