Commerce Layer JS SDK
A JavaScript Library wrapper that makes it quick and easy to interact with the Commerce Layer API.
What is Commerce Layer?
Commerce Layer is a multi-market commerce API and order management system that lets you add global shopping capabilities to any website, mobile app, chatbot, wearable, voice, or IoT device, with ease. Compose your stack with the best-of-breed tools you already mastered and love. Make any experience shoppable, anywhere, through a blazing-fast, enterprise-grade, and secure API.
Getting started
To get started with Commerce Layer JS SDK you need to install it and then get the credentials that will allow you to perform your API calls.
Installation
Commerce Layer JS SDK is available as an npm package:
// npm
npm install @commercelayer/sdk
// yarn
yarn add @commercelayer/sdk
Authentication
All requests to Commerce Layer API must be authenticated with an OAuth2 bearer token.
Hence, before starting to use this SDK you need to get a valid access token.
Check our documentation for more information about the available authorization flows.
Feel free to use Commerce Layer JS Auth, a JavaScript library that helps you wrap our authentication API.
Import
You can use the ES6 default import with the SDK as follow:
import CommerceLayer from '@commercelayer/sdk'
const cl = CommerceLayer({
organization: 'your-organization-slug',
accessToken: 'your-access-token'
})
In the following examples, we will use only the the specific resources we're going to access (SKUs and shipping categories).
Check our API reference for the complete list of available
resources and their attributes.
Usage
The code snippets below show how to use the Commerce Layer JS SDK when performing the standard CRUD operations provided by our REST API on the SKU resource.
-
Create
-
Retrieve / List
-
Update
-
Delete
Create
How to create an SKU
const shippingCategories = await cl.shipping_categories.list({ filters: { name_eq: 'Merchandising' } })
const attributes = {
code: 'TSHIRTMM000000FFFFFFXL',
name: 'Black Men T-shirt with White Logo (XL)',
shipping_category: cl.shipping_categories.relationship(shippingCategories[0].id),
}
const newSku = await cl.skus.create(attributes)
Check our API reference for more information on how to create an SKU.
Retrieve / List
How to fetch a single SKU
const sku = await cl.skus.retrieve('BxAkSVqKEn')
const sku = await cl.skus.list({ filters: { code_eq: 'TSHIRTMM000000FFFFFFXLXX' } })
const sku = (await cl.skus.list()).first()
const sku = (await cl.skus.list()).last()
Check our API reference for more information on how to retrieve an SKU.
How to fetch a collection of SKUs
const skus = await cl.skus.list()
const skus = await cl.skus.list({ sort: { created_at: 'asc' } })
const skus = await cl.skus.list({ sort: { created_at: 'desc' } })
const skus = await cl.skus.list({ include: [ 'prices' ] })
const skus = await cl.skus.list({ fields: { skus: [ 'name', 'metadata' ] } })
const skus = await cl.skus.list({ include: [ 'prices' ], fields: { prices: [ 'currency_code', 'formatted_amount' ] } })
const skus = await cl.skus.list({ filters: { code_start: 'TSHIRT' } })
const skus = await cl.skus.list({ filters: { code_end: 'XLXX' } })
const skus = await cl.skus.list({ filters: { name_cont: 'White Logo' } })
const skus = await cl.skus.list({ filters: { created_at_gt: '2018-01-01', created_at_lt: '2018-01-31'} })
const skus = await cl.skus.list({ filters: { updated_at_or_created_at_gt: '2019-10-10' } })
const skus = await cl.skus.list({ filters: { name_cont: 'Black', shipping_category_name_start: 'MERCH'} })
When fetching a collection of resources you can leverage the meta
attribute to get its meta
information:
const skus = await cl.skus.list()
const meta = skus.meta
Check our API reference for more information on how to list all SKUs, sort the results, use sparse fieldsets, include associations, and filter data.
How to paginate a collection of SKUs
When you fetch a collection of resources, you get paginated results:
const skus = await cl.skus.list({ pageNumber: 3, pageSize: 5 })
const skuCount = skus.meta.recordCount
const pageCount = skus.meta.pageCount
The default page number is 1. The default page size is 10. The maximum page size allowed is 25.
Check our API reference for more information on how pagination works.
How to iterate through a collection of SKUs
To execute a function for every item of a collection, use the map()
method:
const skus = await cl.skus.list()
skus.map(p => console.log('Product: ' + p.name + ' - Code: ' + p.code))
How to fetch resource relationships
Many resources have relationships with other resources and instead of including these associations as seen above, you can fetch them directly.
In this way, in case of 1-to-N relationship, you can filter or sort the resulting collection as for standard resources.
const billingAddress = cl.orders.billing_address('xYZkjABcde')
const orders = cl.customers.orders('XyzKjAbCDe', { fields: ['status', 'number'] })
Update
How to update an existing SKU
const sku = {
id: 'xYZkjABcde',
description: 'Updated description.',
imageUrl: 'https://img.yourdomain.com/skus/new-image.png'
}
cl.skus.update(sku)
Check our API reference for more information on how to update an SKU.
Delete
How to delete an existing SKU
cl.skus.delete('xYZkjABcde')
Check our API reference for more information on how to delete an SKU.
Overriding credentials
If needed, Commerce Layer JS SDK lets you change the client configuration set it at a request level.
To do that, just use the config()
method or pass the options
parameter and authenticate the API call with the desired credentials:
cl.config({ organization: 'you-organization-slug', accessToken: 'your-access-token' })
const skus = await cl.skus.list()
or
cl.skus.list({}, { organization: 'you-organization-slug', accessToken: 'your-access-token' })
Handling validation errors
Commerce Layer API returns specific errors (with extra information) on each attribute of a single resource. You can inspect them to properly handle validation errors (if any). To do that, use the errors
attribute of the catched error:
const attributes = { code: 'TSHIRTMM000000FFFFFFXL', name: '' }
const newSku = await cl.skus.create(attributes).catch(error => console.log(error.errors))
Check our API reference for more information about the errors returned by the API.
License
This repository is published under the MIT license.