### Install Dependencies Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/GenerateSDK.md Run this command to install project dependencies. ```bash yarn install ``` -------------------------------- ### Node.js Installation Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/checkout-sdk/README.md Install the necessary packages for Node.js environments using npm. ```bash npm install --save @commercetools/ts-client npm install --save @commercetools/checkout-sdk ``` -------------------------------- ### Install SDKs in Node.js Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/history-sdk/README.md Install the necessary SDKs for your Node.js project using npm. ```bash npm install --save @commercetools/ts-client npm install --save @commercetools/history-sdk ``` -------------------------------- ### Install SDKs for Node.js Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/platform-sdk/README.md Install the necessary packages for using the commercetools SDKs in a Node.js environment. ```bash npm install --save @commercetools/ts-client npm install --save @commercetools/platform-sdk ``` -------------------------------- ### Browser Environment Setup Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/checkout-sdk/README.md Include these script tags in your HTML to load the SDKs for browser usage. ```html ``` ```javascript // global: @commercetools/ts-client // global: @commercetools/checkout-sdk ;(function () { // We can now access the ts-client and checkout-sdk object as: // const { ClientBuilder } = this['@commercetools/ts-client'] // const { createApiBuilderFromCtpClient } = this['@commercetools/checkout-sdk'] // or // const { ClientBuilder } = window['@commercetools/ts-client'] // const { createApiBuilderFromCtpClient } = window['@commercetools/checkout-sdk'] })() ``` -------------------------------- ### Start Server with OpenTelemetry Collector Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/newrelic-express-apm/README.md Alternatively, start the server using the OpenTelemetry collector. This requires specific OTEL_ variables to be set in your .env file. ```bash node -r ./opentelemetry server.js ``` -------------------------------- ### Install Project Dependencies with Bun Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/vue-example-app/README.md Installs all necessary project dependencies using the bun package manager. This is the first step after cloning the project. ```sh bun install ``` -------------------------------- ### Install Commercetools SDKs Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/sdk-client-v3/README.md Install the necessary packages for the Commercetools TypeScript SDK client using npm or yarn. ```bash npm install --save @commercetools/ts-client npm install --save @commercetools/platform-sdk or yarn add @commercetools/ts-client yarn add @commercetools/platform-sdk ``` -------------------------------- ### Install SDKs in Node.js Environment Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/importapi-sdk/README.md Install the necessary packages for using the ts-client and importapi-sdk in a Node.js project using npm. ```bash npm install --save @commercetools/ts-client npm install --save @commercetools/importapi-sdk ``` -------------------------------- ### Build Projects Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/GenerateSDK.md Execute this command to build the projects after installing dependencies. ```bash yarn build ``` -------------------------------- ### Initialize Client with Old Syntax (Node.js) Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/platform-sdk/README.md Demonstrates initializing the commercetools client using the older syntax with explicit middleware configuration in Node.js. This approach requires manual setup of authentication and HTTP middleware. ```javascript import { createClient, createHttpClient, createAuthForClientCredentialsFlow, } from '@commercetools/ts-client' import { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk' const projectKey = 'some_project_key' const authMiddleware = createAuthForClientCredentialsFlow({ host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey, credentials: { clientId: 'some_id', clientSecret: 'some_secret', }, fetch, }) const httpMiddleware = createHttpClient({ host: 'https://api.europe-west1.gcp.commercetools.com', fetch, }) const ctpClient = createClient({ middlewares: [authMiddleware, httpMiddleware], }) const apiRoot = createApiBuilderFromCtpClient(ctpClient) apiRoot .withProjectKey({ projectKey, }) .get() .execute() .then((x) => { /*...*/ }) apiRoot .withProjectKey({ projectKey }) .productTypes() .post({ body: { name: 'product-type-name', description: 'some description' }, }) .execute() .then((x) => { /*...*/ }) apiRoot .withProjectKey({ projectKey }) .products() .post({ body: { name: { en: 'our-great-product-name' }, productType: { typeId: 'product-type', id: 'some-product-type-id', }, slug: { en: 'some-slug' }, }, }) .execute() .then((x) => { /*...*/ }) ``` -------------------------------- ### Install @commercetools/ts-sdk-apm with npm Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/ts-sdk-apm/README.md Use npm to install the package. This is the first step to integrate APM functionality. ```bash $ npm install @commercetools/ts-sdk-apm ``` -------------------------------- ### Example HTTP Endpoints Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/datadog-express-apm/container-agent/README.md These are example endpoints to curl or send requests to after starting the application. They are used to generate traffic for Datadog to trace. ```http - GET https://localhost:9000/project - GET https://localhost:9000/customers - GET https://localhost:9000/products ``` -------------------------------- ### Install @commercetools/ts-sdk-apm with yarn Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/ts-sdk-apm/README.md Use yarn to install the package. This is an alternative to npm for package management. ```bash $ yarn add @commercetools/ts-sdk-apm ``` -------------------------------- ### Run Development Server with Bun Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/vue-example-app/README.md Starts the development server with hot-reloading enabled, allowing for rapid iteration during development. Uses bun as the task runner. ```sh bun dev ``` -------------------------------- ### Monorepo Structure Example Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/CONTRIBUTING.md The repository is structured as a monorepo, with multiple sub-packages located in the 'packages' directory. ```bash packages/ ... ``` -------------------------------- ### Get Products Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/newrelic-express-apm/requests.txt Retrieves a list of products. ```APIDOC ## GET /products ### Description Retrieves a list of products. ### Method GET ### Endpoint /products ### Request Example ```json { "headers": { "Content-Type": "application/json" }, "body": {} } ``` ``` -------------------------------- ### Node.js Client Configuration (using createClient) Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/checkout-sdk/README.md Configure the Composable Commerce client using the older `createClient` syntax for Node.js. This example shows how to set up authentication and HTTP middleware. ```typescript import { createClient, createHttpClient, createAuthForClientCredentialsFlow, } from '@commercetools/ts-client' import { createApiBuilderFromCtpClient } from '@commercetools/checkout-sdk' const projectKey = 'some_project_key' const authMiddleware = createAuthForClientCredentialsFlow({ host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey, credentials: { clientId: 'some_id', clientSecret: 'some_secret', }, httpClient: fetch, }) const httpMiddleware = createHttpClient({ host: 'https://checkout.europe-west1.gcp.commercetools.com', httpClient: fetch, }) const ctpClient = createClient({ middlewares: [authMiddleware, httpMiddleware], }) const apiRoot = createApiBuilderFromCtpClient(ctpClient) apiRoot .withProjectKey({ projectKey }) .transactions() .post({ body: { application: { typeId: 'application', key: 'checkout-application-key', }, transactionItems: [ { paymentIntegration: { typeId: 'payment-integration', id: 'payment-integration-id', }, amount: { centAmount: 1000, currencyCode: 'EUR', }, }, ], cart: { typeId: 'cart', id: 'cart-id', }, }, }) .execute() .then(...) .catch(...) ``` -------------------------------- ### Start Server with New Relic APM Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/newrelic-express-apm/README.md Run the development server with New Relic APM enabled. Ensure your .env file is populated with necessary credentials and New Relic license key. ```bash yarn start ``` -------------------------------- ### Get Project Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/newrelic-express-apm/requests.txt Fetches the current project details. ```APIDOC ## GET /project ### Description Fetches the current project details. ### Method GET ### Endpoint /project ### Request Example ```json { "headers": { "Content-Type": "application/json" }, "body": {} } ``` ``` -------------------------------- ### Get Customers Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/newrelic-express-apm/requests.txt Retrieves a list of customers. ```APIDOC ## GET /customers ### Description Retrieves a list of customers. ### Method GET ### Endpoint /customers ### Request Example ```json { "headers": { "Content-Type": "application/json" }, "body": {} } ``` ``` -------------------------------- ### Example Endpoints for Dynatrace APM Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/dynatrace-express-apm/README.md These are example HTTP endpoints to test the Dynatrace APM integration. Send requests to these endpoints using any HTTP client to observe monitoring data. ```http GET https://localhost:9000/project GET https://localhost:9000/customers GET https://localhost:9000/products ``` -------------------------------- ### Node.js Client Configuration (Client Credentials Flow) Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/checkout-sdk/README.md Configure the Composable Commerce client using the Client Credentials Flow for Node.js. This example demonstrates setting up authentication and HTTP middleware. ```typescript const { ClientBuilder, createAuthForClientCredentialsFlow, createHttpClient, } = require('@commercetools/ts-client') const { createApiBuilderFromCtpClient } = require('@commercetools/checkout-sdk') const projectKey = 'mc-project-key' const authMiddlewareOptions = { host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey, credentials: { clientId: 'mc-client-id', clientSecret: 'mc-client-secrets', }, oauthUri: '/oauth/token', // - optional: custom oauthUri scopes: [`manage_project:${projectKey}`], fetch, } const httpMiddlewareOptions = { host: 'https://checkout.europe-west1.gcp.commercetools.com', fetch, } const client = new ClientBuilder() .withProjectKey(projectKey) .withMiddleware(createAuthForClientCredentialsFlow(authMiddlewareOptions)) .withMiddleware(createHttpClient(httpMiddlewareOptions)) .withUserAgentMiddleware() .build() // or const client = new ClientBuilder() .withProjectKey(projectKey) .withClientCredentialsFlow(authMiddlewareOptions) .withHttpMiddleware(httpMiddlewareOptions) .withUserAgentMiddleware() .build() const apiRoot = createApiBuilderFromCtpClient(client) // calling the checkout-sdk functions // create a new transaction using the checkout sdk apiRoot .withProjectKey({ projectKey }) .transactions() .post({ body: { application: { typeId: 'application', key: 'checkout-application-key', }, transactionItems: [ { paymentIntegration: { typeId: 'payment-integration', id: 'payment-integration-id', }, amount: { centAmount: 1000, currencyCode: 'EUR', }, }, ], cart: { typeId: 'cart', id: 'cart-id', }, }, }) .execute() .then(...) .catch(...) ``` -------------------------------- ### Get Project Details in Browser Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/browser/browser.html Fetches project details and displays them in the browser. Ensure the DOM element with ID 'details' exists. ```javascript function getProjectDetails() { var oauthUri = 'https://auth.europe-west1.gcp.commercetools.com' var baseUri = 'https://api.europe-west1.gcp.commercetools.com' var credentials = { clientId: '', clientSecret: '' } var projectKey = ''; var { ClientBuilder } = this ['@commercetools/ts-client']; var client = new ClientBuilder() .defaultClient(baseUri, credentials, oauthUri, projectKey) .build(); var { createApiBuilderFromCtpClient } = this ['@commercetools/platform-sdk']; var apiRoot = createApiBuilderFromCtpClient(client); apiRoot .withProjectKey({ projectKey }) .get() .execute() .then(function ({ body }) { window.document.getElementById('details').innerHTML = JSON.stringify(body, null, 2); }); } ``` -------------------------------- ### Example API Endpoints Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/newrelic-express-apm/README.md Send requests to these endpoints using any HTTP client to generate traffic and observe metrics in New Relic. ```http GET https://localhost:8000/project GET https://localhost:8000/customers GET https://localhost:8000/products GET https://localhost:8000/cart GET https://localhost:8000/cart-discount ``` -------------------------------- ### Make API Calls with History SDK (Node.js - Old Syntax) Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/history-sdk/README.md Example calls to the history SDK's project categories and image search endpoints using the client initialized with the old syntax. ```typescript apiRoot .withProjectKey({ projectKey }) .recommendations() .projectCategories() .withProductId({ productId: product.id, }) .get() .execute() .then((x) => { /*...*/ }) apiRoot .withProjectKey({ projectKey }) .imageSearch() .post({ queryArgs: { limit: 20, }, body: image, headers: { 'Content-Type': 'image/jpeg', }, }) .execute() .then((x) => { /*...*/ }) ``` -------------------------------- ### Make API Calls with History SDK (Node.js) Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/history-sdk/README.md Example calls to the history SDK's project categories and image search endpoints after client initialization. ```typescript // calling the history-sdk functions // get project details apiRoot .withProjectKey({ projectKey }) .recommendations() .projectCategories() .withProductId({ productId: product.id, }) .get() .execute() .then((x) => { /*...*/ }) apiRoot .withProjectKey({ projectKey }) .imageSearch() .post({ queryArgs: { limit: 20, }, body: image, headers: { 'Content-Type': 'image/jpeg', }, }) .execute() .then((x) => { /*...*/ }) ``` -------------------------------- ### Build Client with Mixed Middleware Order Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/sdk-client-v3/README.md Demonstrates adding a custom middleware using `withMiddleware` alongside built-in middleware methods. Custom middleware added via `withMiddleware` is placed at the start of the execution chain. ```typescript // Example const authMiddlewareOptions = { credentials: { clientId: 'xxx', clientSecret: 'xxx', }, host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey: 'xxx', } const httpMiddlewareOptions = { host: 'https://api.europe-west1.gcp.commercetools.com', httpClient: fetch, } const logger = () => { return (next) => async (request) => { // log request object console.log('Request:', request) const response = await next(request) // log response object console.log('Response', response) return response } } const client = new ClientBuilder() .withClientCredentialsFlow(authMiddlewareOptions) .withHttpMiddleware(httpMiddlewareOptions) .withConcurrentModificationMiddleware() .withMiddleware(logger()) .build() ``` -------------------------------- ### Get Cart Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/newrelic-express-apm/requests.txt Retrieves the current shopping cart. Requires an authorization token. ```APIDOC ## GET /cart ### Description Retrieves the current shopping cart. Requires an authorization token. ### Method GET ### Endpoint /cart ### Request Example ```json { "headers": { "Content-Type": "application/json", "Authorization": "Bearer " }, "body": {} } ``` ``` -------------------------------- ### Get Cart Discount Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/newrelic-express-apm/requests.txt Retrieves a specific cart discount by its ID. Requires an authorization token. ```APIDOC ## GET /cart-discount ### Description Retrieves a specific cart discount by its ID. Requires an authorization token. ### Method GET ### Endpoint /cart-discount ### Request Body - **id** (string) - Required - The ID of the cart discount to retrieve. ### Request Example ```json { "headers": { "Content-Type": "application", "Authorization": "Bearer " }, "body": { "id": "" } } ``` ``` -------------------------------- ### Send Request to Error Endpoint with cURL Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/fastify/README.md Use this command to send a GET request to the Fastify server's error endpoint, which is configured to simulate a commercetools concurrent modification error. ```bash # using curl to send a request to the error endpoint curl http://127.0.0.1:3000/update-project-error ``` -------------------------------- ### Send Request to Success Endpoint with cURL Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/fastify/README.md Use this command to send a GET request to the Fastify server's success endpoint. This endpoint demonstrates how the SDK's middleware handles concurrent modification errors, leading to a successful response. ```bash # using curl to send a request to the success endpoint curl http://127.0.0.1:3000/update-project-error ``` -------------------------------- ### Generate SDKs Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/GenerateSDK.md Run this command to generate the SDKs. Ensure environment variables are set beforehand. ```bash yarn generate ``` -------------------------------- ### Initialize Client and API Builder (Node.js - Method 1) Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/importapi-sdk/README.md Set up the commercetools client using ClientBuilder with authentication and HTTP middleware, then create the Import API builder. ```javascript const { ClientBuilder, createAuthForClientCredentialsFlow, createHttpClient, } = require('@commercetools/ts-client') const { createApiBuilderFromCtpClient } = require('@commercetools/importapi-sdk') const projectKey = 'mc-project-key' const authMiddlewareOptions = { host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey, credentials: { clientId: 'mc-client-id', clientSecret: 'mc-client-secrets', }, oauthUri: '/oauth/token', // - optional: custom oauthUri scopes: [`manage_project:${projectKey}`], fetch, } const httpMiddlewareOptions = { host: 'https://import.europe-west1.gcp.commercetools.com', fetch, } const client = new ClientBuilder() .withProjectKey(projectKey) .withMiddleware(createAuthForClientCredentialsFlow(authMiddlewareOptions)) .withMiddleware(createHttpClient(httpMiddlewareOptions)) .withUserAgentMiddleware() .build() // or const client = new ClientBuilder() .withProjectKey(projectKey) .withClientCredentialsFlow(authMiddlewareOptions) .withHttpMiddleware(httpMiddlewareOptions) .withUserAgentMiddleware() .build() const apiRoot = createApiBuilderFromCtpClient(client) // calling the importapi functions // get project details apiRoot .withProjectKeyValue({ projectKey, }) .importContainers() .get() .execute() .then((x) => { /*...*/ }) ``` -------------------------------- ### Initialize Client with Client Credentials Flow (Node.js) Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/platform-sdk/README.md Set up the commercetools client using the ClientBuilder and Client Credentials Flow for authentication in Node.js. Ensure you provide valid project key, authentication host, API host, and credentials. ```javascript const { ClientBuilder, createAuthForClientCredentialsFlow, createHttpClient, } = require('@commercetools/ts-client') const { createApiBuilderFromCtpClient } = require('@commercetools/platform-sdk') const projectKey = 'mc-project-key' const authMiddlewareOptions = { host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey, credentials: { clientId: 'mc-client-id', clientSecret: 'mc-client-secrets', }, oauthUri: '/oauth/token', // - optional: custom oauthUri scopes: [`manage_project:${projectKey}`], fetch, } const httpMiddlewareOptions = { host: 'https://api.europe-west1.gcp.commercetools.com', fetch, } const client = new ClientBuilder() .withProjectKey(projectKey) .withMiddleware(createAuthForClientCredentialsFlow(authMiddlewareOptions)) .withMiddleware(createHttpClient(httpMiddlewareOptions)) .withUserAgentMiddleware() .build() // or const client = new ClientBuilder() .withProjectKey(projectKey) .withClientCredentialsFlow(authMiddlewareOptions) .withHttpMiddleware(httpMiddlewareOptions) .withUserAgentMiddleware() .build() const apiRoot = createApiBuilderFromCtpClient(client) // calling the platform functions // get project details apiRoot .withProjectKey({ projectKey, }) .get() .execute() .then((x) => { /*...*/ }) // create a productType apiRoot .withProjectKey({ projectKey }) .productTypes() .post({ body: { name: 'product-type-name', description: 'some description' }, }) .execute() .then((x) => { /*...*/ }) // create a product apiRoot .withProjectKey({ projectKey }) .products() .post({ body: { name: { en: 'our-great-product-name' }, productType: { typeId: 'product-type', id: 'some-product-type-id', }, slug: { en: 'some-slug' }, }, }) .execute() .then((x) => { /*...*/ }) ``` -------------------------------- ### Initialize Client and API Builder in Node.js (Method 2 - Old Syntax) Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/history-sdk/README.md Initialize the Commercetools client using createClient and create the API builder for the history SDK. This method uses an array of middlewares. ```typescript import { createClient, createHttpClient, createAuthForClientCredentialsFlow, } from '@commercetools/ts-client' import { createApiBuilderFromCtpClient } from '@commercetools/history-sdk' const projectKey = 'some_project_key' const authMiddleware = createAuthForClientCredentialsFlow({ host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey, credentials: { clientId: 'some_id', clientSecret: 'some_secret', }, fetch, }) const httpMiddleware = createHttpClient({ host: 'https://history.europe-west1.gcp.commercetools.com', fetch, }) const ctpClient = createClient({ middlewares: [authMiddleware, httpMiddleware], }) const apiRoot = createApiBuilderFromCtpClient(ctpClient) ``` -------------------------------- ### Initialize Commercetools API Client Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/BEST_PRACTICES.md Demonstrates the recommended way to create a Commercetools API client using `ClientBuilder`. Ensure environment variables for credentials and API host are set. ```typescript import { ClientBuilder } from '@commercetools/ts-client' const projectKey = 'your-project-key' const authMiddlewareOptions = { host: process.env.CTP_API_HOST, projectKey, credentials: { clientId: process.env.CTP_CLIENT_ID, clientSecret: process.env.CTP_CLIENT_SECRET, }, scopes: [process.env.CTP_API_SCOPES], httpClient: fetch, } const httpMiddlewareOptions = { host: process.env.CTP_API_HOST, includeRequestInErrorResponse: true, // Include request in error responses includeOriginalRequest: true, // Include request in successful responses httpClient: fetch, } const client = new ClientBuilder() .withProjectKey(projectKey) .withClientCredentialsFlow(authMiddlewareOptions) .withHttpMiddleware(httpMiddlewareOptions) .withUserAgentMiddleware() .withLoggerMiddleware() // Optional: for logging requests .build() ``` -------------------------------- ### Initialize Client and API Builder (Node.js - Method 2) Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/importapi-sdk/README.md Initialize the commercetools client using createClient with explicit middleware, then create the Import API builder. This demonstrates an alternative initialization pattern. ```javascript import { createClient, createHttpClient, createAuthForClientCredentialsFlow, } from '@commercetools/ts-client' import { createApiBuilderFromCtpClient } from '@commercetools/importapi-sdk') const projectKey = 'some_project_key' const authMiddleware = createAuthForClientCredentialsFlow({ host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey, credentials: { clientId: 'some_id', clientSecret: 'some_secret', }, fetch, }) const httpMiddleware = createHttpClient({ host: 'https://import.europe-west1.gcp.commercetools.com', fetch, }) const ctpClient = createClient({ middlewares: [authMiddleware, httpMiddleware], }) const apiRoot = createApiBuilderFromCtpClient(ctpClient) apiRoot .withProjectKey({ projectKey, }) .get() .execute() .then((x) => { /*...*/ }) ``` -------------------------------- ### Import API Client Initialization and Usage Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/importapi-sdk/README.md Demonstrates how to initialize the commercetools TypeScript client and use the Import API SDK to interact with import containers. ```APIDOC ## Initialize Client and API Builder This section shows how to set up the commercetools client with authentication and HTTP middleware, and then create an API builder for the Import API. ### Node.js Environment Setup ```ts const { ClientBuilder, createAuthForClientCredentialsFlow, createHttpClient } = require('@commercetools/ts-client') const { createApiBuilderFromCtpClient } = require('@commercetools/importapi-sdk') const projectKey = 'mc-project-key' const authMiddlewareOptions = { host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey, credentials: { clientId: 'mc-client-id', clientSecret: 'mc-client-secrets', }, scopes: [`manage_project:${projectKey}`], fetch, } const httpMiddlewareOptions = { host: 'https://import.europe-west1.gcp.commercetools.com', fetch, } const client = new ClientBuilder() .withProjectKey(projectKey) .withMiddleware(createAuthForClientCredentialsFlow(authMiddlewareOptions)) .withMiddleware(createHttpClient(httpMiddlewareOptions)) .withUserAgentMiddleware() .build() const apiRoot = createApiBuilderFromCtpClient(client) ``` ### Calling Import API Functions This example demonstrates how to call the `get` method on import containers after initializing the API builder. ```ts // get project details apiRoot .withProjectKeyValue({ projectKey, }) .importContainers() .get() .execute() .then((x) => { // Handle response }) ``` ### Alternative Client Initialization (Old Syntax) This shows an alternative way to create the client using `createClient`. ```ts import { createClient, createHttpClient, createAuthForClientCredentialsFlow, } from '@commercetools/ts-client' import { createApiBuilderFromCtpClient } from '@commercetools/importapi-sdk' const projectKey = 'some_project_key' const authMiddleware = createAuthForClientCredentialsFlow({ host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey, credentials: { clientId: 'some_id', clientSecret: 'some_secret', }, fetch, }) const httpMiddleware = createHttpClient({ host: 'https://import.europe-west1.gcp.commercetools.com', fetch, }) const ctpClient = createClient({ middlewares: [authMiddleware, httpMiddleware], }) const apiRoot = createApiBuilderFromCtpClient(ctpClient) apiRoot .withProjectKey({ projectKey, }) .get() .execute() .then((x) => { // Handle response }) ``` ``` -------------------------------- ### Build for Production with Bun Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/vue-example-app/README.md Compiles and minifies the project for production deployment. This command is used to prepare the application for a production environment. ```sh bun run build ``` -------------------------------- ### Initialize Client and API Builder in Node.js (Method 1) Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/history-sdk/README.md Initialize the Commercetools client using ClientBuilder and create the API builder for the history SDK. This method uses separate middleware configurations. ```typescript const { ClientBuilder, createAuthForClientCredentialsFlow, createHttpClient, } = require('@commercetools/ts-client') const { createApiBuilderFromCtpClient } = require('@commercetools/history-sdk') const projectKey = 'mc-project-key' const authMiddlewareOptions = { host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey, credentials: { clientId: 'mc-client-id', clientSecret: 'mc-client-secrets', }, oauthUri: '/oauth/token', // - optional: custom oauthUri scopes: [`manage_project:${projectKey}`], fetch, } const httpMiddlewareOptions = { host: 'https://history.europe-west1.gcp.commercetools.com', fetch, } const client = new ClientBuilder() .withProjectKey(projectKey) .withMiddleware(createAuthForClientCredentialsFlow(authMiddlewareOptions)) .withMiddleware(createHttpClient(httpMiddlewareOptions)) .withUserAgentMiddleware() .build() // or const client = new ClientBuilder() .withProjectKey(projectKey) .withClientCredentialsFlow(authMiddlewareOptions) .withHttpMiddleware(httpMiddlewareOptions) .withUserAgentMiddleware() .build() const apiRoot = createApiBuilderFromCtpClient(client) ``` -------------------------------- ### Initialize Commercetools Client with Custom Middleware Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/sdk-client-v3/README.md Demonstrates initializing the Commercetools TypeScript SDK client with password flow authentication, logger middleware, correlation ID middleware, HTTP middleware, and a custom middleware. Ensure all necessary imports are included. ```typescript import { type Next, type HttpMiddlewareOptions, type AuthMiddlewareBaseOptions, type ClientRequest, type MiddlewareRequest, type MiddlewareResponse, type Client, createHttpMiddleware, createConcurrentModificationMiddleware, createAuthMiddlewareForClientCredentialsFlow, ClientBuilder, } from '@commercetools/ts-client' import { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk' const projectKey = 'mc-project-key' const authMiddlewareOptions = { host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey, credentials: { clientId: 'mc-client-id', clientSecret: 'mc-client-secrets', }, oauthUri: '/oauth/token', // - optional: custom oauthUri scopes: [`manage_project:${projectKey}`], httpClient: fetch, } const httpMiddlewareOptions = { host: 'https://api.europe-west1.gcp.commercetools.com', httpClient: fetch, } const retryOptions = { maxRetries: 3, retryDelay: 200, backoff: true, retryCodes: [503], } const loggerFn = (response) => { // log response object console.log(response) } // custom middleware function middleware(options) { return (next: Next) => async (request: MiddlewareRequest): Promise => { const { response, ...rest } = request // other actions can also be carried out here e.g logging, // error handling, injecting custom headers to http requests etc. console.log({ response, rest }) return next({ ...request }) } } const client: Client = new ClientBuilder() .withPasswordFlow(authMiddlewareOptions) .withLoggerMiddleware({ loggerFn }) .withCorrelationIdMiddleware({ generate: () => 'fake-correlation-id' + Math.floor(Math.random() + 2), }) .withHttpMiddleware(httpMiddlewareOptions) .withMiddleware(middleware({})) // <<<------------------- add the custom middleware here .build() const apiRoot = createApiBuilderFromCtpClient(client) // calling the Composable Commerce `api` functions // get project details apiRoot .withProjectKey({ projectKey }) .get() .execute() .then((x) => { /*...*/ }) // create a productType apiRoot .withProjectKey({ projectKey }) .productTypes() .post({ body: { name: 'product-type-name', description: 'some description' }, }) .execute() .then((x) => { /*...*/ }) // create a product apiRoot .withProjectKey({ projectKey }) .products() .post({ body: { name: { en: 'our-great-product-name' }, productType: { typeId: 'product-type', id: 'some-product-type-id', }, slug: { en: 'some-slug' }, }, }) .execute() .then((x) => { /*...*/ }) ``` -------------------------------- ### Build Client with Ordered Middleware via withMiddleware Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/sdk-client-v3/README.md Add multiple middleware functions, including custom ones like a logger, to the client in a specific execution order using the `withMiddleware` method. ```typescript // Example const authMiddlewareOptions = { credentials: { clientId: 'xxx', clientSecret: 'xxx', }, host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey: 'xxx', } const httpMiddlewareOptions = { host: 'https://api.europe-west1.gcp.commercetools.com', httpClient: fetch, } const logger = () => { return (next) => async (request) => { // log request object console.log('Request:', request) const response = await next(request) // log response object console.log('Response', response) return response } } const client = new ClientBuilder() .withMiddleware( createAuthMiddlewareForClientCredentialsFlow(authMiddlewareOptions) ) .withMiddleware(createHttpMiddleware(httpMiddlewareOptions)) .withMiddleware(createConcurrentModificationMiddleware()) .withMiddleware(logger()) .build() ``` -------------------------------- ### Client Environment Configuration Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/me/README.md Configure the client environment variables for the Composable Commerce ME endpoint checkout app. This sets the base URL for the server. ```txt REACT_APP_BASE_URL=http://localhost:8085 ``` -------------------------------- ### Create Cart Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/newrelic-express-apm/requests.txt Creates a new shopping cart with specified currency and customer email. Requires an authorization token. ```APIDOC ## POST /cart ### Description Creates a new shopping cart with specified currency and customer email. Requires an authorization token. ### Method POST ### Endpoint /cart ### Request Body - **currency** (string) - Required - The currency for the cart. - **customerEmail** (string) - Required - The email address of the customer. ### Request Example ```json { "headers": { "Content-Type": "application/json", "Authorization": "Bearer " }, "body": { "currency": "EUR", "customerEmail": "test.one@mail.com" } } ``` ``` -------------------------------- ### Server Environment Configuration Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/me/README.md Configure the server environment variables for the Composable Commerce ME endpoint checkout app. Ensure all placeholders are replaced with your API client's credentials. ```bash PORT=8085 CTP_CLIENT_ID={clientID} CTP_PROJECT_KEY={projectKey} CTP_CLIENT_SECRET={clientSecret} CTP_AUTH_URL={authUrl} CTP_API_URL={hostUrl} DEFAULT_CURRENCY=EUR ``` -------------------------------- ### Include SDKs in Browser Environment Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/importapi-sdk/README.md Include these script tags in your HTML to make the ts-client and importapi-sdk available globally in the browser. ```html ``` ```javascript ;(function () { // We can now access the ts-client and importapi-sdk object as: // const { ClientBuilder } = this['@commercetools/ts-client'] // const { createApiBuilderFromCtpClient } = this['@commercetools/importapi-sdk'] // or // const { ClientBuilder } = window['@commercetools/ts-client'] // const { createApiBuilderFromCtpClient } = window['@commercetools/importapi-sdk'] })() ``` -------------------------------- ### Include SDKs in Browser Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/platform-sdk/README.md Include these script tags to load the commercetools TS-client and platform-sdk in a browser environment. ```html ``` ```javascript ;(function () { // We can now access the ts-client and platform-sdk object as: // const { ClientBuilder } = this['@commercetools/ts-client'] // const { createApiBuilderFromCtpClient } = this['@commercetools/platform-sdk'] // or // const { ClientBuilder } = window['@commercetools/ts-client'] // const { createApiBuilderFromCtpClient } = window['@commercetools/platform-sdk'] })() ``` -------------------------------- ### Include SDKs in Browser Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/history-sdk/README.md Include these script tags to load the ts-client and history-sdk in a browser environment. ```html ``` -------------------------------- ### Useful Yarn Commands Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/CONTRIBUTING.md Commonly used Yarn commands for working with the repository, including testing, type checking, and building packages. ```bash yarn test and yarn test --watch yarn typecheck yarn build ``` -------------------------------- ### Configure HTTP Client with Proxy Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/BEST_PRACTICES.md Configure proxies at the HTTP client level by passing a custom fetch function that includes proxy settings using 'https-proxy-agent'. ```typescript import HttpsProxyAgent from 'https-proxy-agent' const fetcherProxy = (url, fetchOptions = {}) => { fetchOptions.agent = new HttpsProxyAgent('proxy-url/ip-address') // e.g http://76.253.101.51:8080 return fetch(url, fetchOptions) } const httpMiddlewareOptions = { //... httpClient: fetcherProxy, //... } ``` -------------------------------- ### Build Client with Built-in Middleware Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/sdk-client-v3/README.md Configure and build a client using the `ClientBuilder` with common built-in middleware options like HTTP, concurrent modification, and client credentials flow. ```typescript const authMiddlewareOptions = { credentials: { clientId: 'xxx', clientSecret: 'xxx', }, host: 'https://auth.europe-west1.gcp.commercetools.com', projectKey: 'xxx', } const httpMiddlewareOptions = { host: 'https://api.europe-west1.gcp.commercetools.com', httpClient: fetch, } const client = new ClientBuilder() .withHttpMiddleware(httpMiddlewareOptions) .withConcurrentModificationMiddleware() .withClientCredentialsFlow(authMiddlewareOptions) .build() ``` -------------------------------- ### Integrate Telemetry Middleware with SDK Client Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/ts-sdk-apm/README.md Import and add the telemetry middleware to your SDK client builder. Ensure New Relic options are correctly configured. ```typescript // import the @commercetools/ts-sdk-apm package import { ClientBuilder } from '@commercetools/ts-client' import { createTelemetryMiddleware } from '@commercetools/ts-sdk-apm' // newrelic options const telemetryOptions = { createTelemetryMiddleware } // create the client and include the telemetry middleware const client = new ClientBuilder() .withClientCredentialsFlow(...) .withHttpMiddleware(...) .withTelemetryMiddleware(telemetryOptions) // telemetry middleware ... .build() ... ``` -------------------------------- ### Define Telemetry Options with Custom Tracer and Metrics Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/packages/ts-sdk-apm/README.md Configure telemetry options, including a custom tracer and custom metrics for New Relic or Datadog. Ensure the tracer requires an absolute path. ```typescript type telemetryOptions = { createTelemetryMiddleware: (options: Omit) => Middleware, apm?: () => typeof require('newrelic'), tracer?: () => typeof require('/absolute-path-to-a-tracer(opentelemetry)-module'), customMetrics?: { newrelic?: true; datadog?: false; // it can be omitted } } ``` ```typescript const telemetryOptions = { createTelemetryMiddleware, tracer: () => require( require('path').join(__dirname, '..', '..', 'custom-telemetry-module.js') ), // make sure the require takes in an absolute path to the custom tracer module. customMetrics: { datadog: true, }, } ``` -------------------------------- ### Process Batch Requests with commercetools SDK Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/BEST_PRACTICES.md Use the `Process` function to handle batch requests. It takes a request, a processing function, and options for total requests and accumulation. The `accumulate` option defaults to `true`, returning an array of results. ```typescript import { Process, ClientBuilder } from '@commercetools/ts-client' import { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk' //... const apiRoot = new ClientBuilder() .withProjectKey(projectKey) .withClientCredentialsFlow(authMiddlewareOptions) .withHttpMiddleware(httpMiddlewareOptions) .build() // prepare the batch request here. const request = await apiRoot.categories().withId({ ID: 'category-id-1' }).get() .clientRequest // this can be any custom batch processing function const processFn = (data) => data const opt = { total: 10, // total request to be processed accumulate: true, // accumulate all the processed result into an array, default `true` } Process(request, processFn, opt) .then((response) => { // response is an array of processed results expect(response[0].body.key).toEqual(process.env.CTP_PROJECT_KEY) }) .catch(console.error) ``` -------------------------------- ### Create Cart Discount Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/examples/newrelic-express-apm/requests.txt Creates a new cart discount with various configuration options. Requires an authorization token. ```APIDOC ## POST /cart-discount ### Description Creates a new cart discount with various configuration options. Requires an authorization token. ### Method POST ### Endpoint /cart-discount ### Request Body - **key** (string) - Required - A unique identifier for the cart discount. - **name** (object) - Required - The name of the cart discount, localized. - **en** (string) - Required - The English name. - **value** (object) - Required - The discount value. - **type** (string) - Required - Type of discount (e.g., 'relative'). - **permyriad** (number) - Required - The discount percentage (per 10,000). - **cartPredicate** (string) - Required - The predicate to determine when the discount applies. - **target** (object) - Required - The target of the discount. - **type** (string) - Required - Type of target (e.g., 'shipping'). - **sortOrder** (string) - Optional - The order in which the discount is applied. - **requiresDiscountCode** (boolean) - Optional - Whether a discount code is required. - **isActive** (boolean) - Optional - Whether the discount is currently active. ### Request Example ```json { "headers": { "Content-Type": "application/json", "Authorization": "Bearer " }, "body": { "key": "b2c0f765-93b1-4b01-890d-6d6850cfd7bf", "name": { "en": "test-name-cartDiscount-1234567890" }, "value": { "type": "relative", "permyriad": 10 }, "cartPredicate": "'country='DE'", "target": { "type": "shipping" }, "sortOrder": "0.65141", "requiresDiscountCode": true, "isActive": false } } ``` ``` -------------------------------- ### Execute Custom Platform Requests Source: https://github.com/commercetools/commercetools-sdk-typescript/blob/master/BEST_PRACTICES.md Use the `execute` function on the client to manually construct and send requests directly to the platform when SDK methods are not available for specific endpoints. ```typescript const request = { uri: '/constructed-request', // e.g - `/${projectKey}/in-store/key=${storeKey}/customers/token`, method: 'GET', headers: { Authorization: 'Bearer xxx', }, } client .execute(request) .then((result) => {}) .catch((error) => {}) ```