Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@commercetools/ts-client

commercetools310.4kMIT3.3.0TypeScript support: included

commercetools Composable Commerce TypeScript SDK client.

commercetools, composable commerce, sdk, typescript, client, middleware, http, oauth, auth

readme

Commercetools Composable Commerce (Improved) TypeScript SDK client

This is the new and improved Typescript SDK client.

Usage examples

npm install --save @commercetools/ts-client
npm install --save @commercetools/platform-sdk

or

yarn add @commercetools/ts-client
yarn add @commercetools/platform-sdk
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<MiddlewareResponse> => {
      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) => {
    /*...*/
  })

Create a client

To create a client, use the ClientBuilder class. The ClientBuilder class provides a fluent API to configure the client.

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()

The withMiddleware method can be used to add middleware functions (both built-in and custom middleware) in an ordered fashion.

// 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()

This will add the middleware in an ordered fashion starting with the:

  1. createAuthMiddlewareForClientCredentialsFlow
  2. createHttpMiddleware
  3. createConcurrentModificationMiddleware
  4. logger

Note that when using the withMiddleware function to add a custom middleware along side other in built middleware functions, it will add the custom middleware to the start of the execution chain.

// 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()

The order of execution is as follows:

  1. withMiddleware <------ the custom middleware
  2. withClientCredentialsFlow
  3. withHttpMiddleware
  4. withConcurrentModificationMiddleware

changelog

@commercetools/ts-client

3.3.0

Minor Changes

3.2.2

Patch Changes

3.2.1

Patch Changes

  • #1009 7473c1c Thanks @ajimae! - Fix issue with user-agents in unknown environments e.g react-native

3.2.0

Minor Changes

3.1.1

Patch Changes

3.1.0

Minor Changes

Patch Changes

  • #924 e002f9d Thanks @ajimae! - map returned error code field to commercetools error response code

3.0.4

Patch Changes

3.0.3

Patch Changes

3.0.2

Patch Changes

3.0.1

Patch Changes

3.0.0

Major Changes

2.1.7

Patch Changes

2.1.6

Patch Changes

  • #884 3bfcd2e Thanks @ajimae! - [Fix][DEVX-514] Fix v3 AbortController Retry Reinitialization

2.1.5

Patch Changes

  • #864 2d622a1 Thanks @ajimae! - Fix issue with sdk-client-v3 returning undefined body on error

2.1.4

Patch Changes

2.1.3

Patch Changes

2.1.2

Patch Changes

  • #848 39c5298 Thanks @ajimae! - - add httpClientOptions to all supported authMiddlewareOption and httpMiddlewareOptions
    • add options used for configuring the behaviour of the supported httpClients (fetch and axios)

2.1.1

Patch Changes

2.1.0

Minor Changes

2.0.5

Patch Changes

2.0.4

Patch Changes

2.0.3

Patch Changes

2.0.2

Patch Changes

2.0.1

Patch Changes

  • #767 d82a9e0 Thanks @ajimae! - Fix issues with request state not being reset back to default on error when fetching token.

2.0.0

Major Changes

1.2.1

Patch Changes

1.2.0

Minor Changes

1.1.1

Patch Changes

1.1.0

Minor Changes

1.0.0

Major Changes

  • #434 ea0a6c6 Thanks @ajimae! - Introduce the new typescript client package with the following eatures and middleware
    • <input checked="" disabled="" type="checkbox"> add client and middleware composer
    • <input checked="" disabled="" type="checkbox"> add http-middleware
    • <input checked="" disabled="" type="checkbox"> add error-middleware
    • <input checked="" disabled="" type="checkbox"> add logger-middleware
    • <input checked="" disabled="" type="checkbox"> add auth-middleware
      • <input checked="" disabled="" type="checkbox"> add with-client-credentials-flow
      • <input checked="" disabled="" type="checkbox"> add with-anonymous-session-flow
      • <input checked="" disabled="" type="checkbox"> add with-password-flow
      • <input checked="" disabled="" type="checkbox"> add with-refresh-token-flow
      • <input checked="" disabled="" type="checkbox"> add with-existing-token-flow
      • <input checked="" disabled="" type="checkbox"> add token cache
    • <input checked="" disabled="" type="checkbox"> add retry-middleware
    • <input checked="" disabled="" type="checkbox"> add correlation-id-middleware
    • <input checked="" disabled="" type="checkbox"> add queue-middleware
    • <input checked="" disabled="" type="checkbox"> add user-agent-middleware
    • <input checked="" disabled="" type="checkbox"> add concurrent-modification-middleware
    • <input checked="" disabled="" type="checkbox"> add axios and node-fetch support