Gathering detailed insights and metrics for @commercelayer/provisioning-sdk
Gathering detailed insights and metrics for @commercelayer/provisioning-sdk
Gathering detailed insights and metrics for @commercelayer/provisioning-sdk
Gathering detailed insights and metrics for @commercelayer/provisioning-sdk
npm install @commercelayer/provisioning-sdk
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (94.38%)
Smarty (5.35%)
JavaScript (0.27%)
Total Downloads
15,099
Last Day
17
Last Week
93
Last Month
492
Last Year
10,221
MIT License
201 Commits
2 Watchers
9 Branches
22 Contributors
Updated on Apr 07, 2025
Minified
Minified + Gzipped
Latest Version
2.5.1
Package Id
@commercelayer/provisioning-sdk@2.5.1
Unpacked Size
183.21 kB
Size
36.70 kB
File Count
7
NPM Version
10.9.2
Node Version
22.14.0
Published on
Apr 07, 2025
Cumulative downloads
Total Downloads
Last Day
750%
17
Compared to previous day
Last Week
27.4%
93
Compared to previous week
Last Month
-39.9%
492
Compared to previous month
Last Year
109.5%
10,221
Compared to previous year
A JavaScript Library wrapper that makes it quick and easy to interact with the Commerce Layer Provisioning API.
To get started with Commerce Layer Provisioning SDK you need to install it, get the credentials that will allow you to perform your API calls, and import the SDK into your application's code. The sections below explain how to achieve this.
Commerce Layer Provisioning SDK is available as an npm and yarn package that you can install with the command below:
1npm install @commercelayer/provisioning-sdk 2 3// or 4 5yarn add @commercelayer/provisioning-sdk
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. Kindly 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.
You can use the ES6 default import with the SDK like so:
1import CommerceLayerProvisioning from '@commercelayer/provisioning-sdk' 2 3const cl = CommerceLayer({ 4 accessToken: 'your-access-token' 5})
When instantiating a new SDK client you can pass some options to initialize it:
1{ 2 accessToken: string // A valid API access token 3 timeout?: number // A custom request timout (<= 15 secs [default]) 4 headers?: RequestHeaders // Custom request headers 5 userAgent?: string // Custom user-agent useful in certaing contexts but often not allowed by browsers 6 fetch?: Fetch // A specific fetch implementation 7 refreshToken?: RefreshToken // A function responsible for token refresh 8}
Same options can be changed after SDK initialization or passed at runtime while executing an API call:
1 const options = { ... } 2 3 // Instantiate the client using desired options 4 const clp = CommerceLayer(options) 5 6 // Change configuration after client cteation 7 clp.config(options) 8 9 // Use runtime configuration without persisting settings 10 clp.customers.organizations({}, options)
The JavaScript Provisioning SDK is a wrapper around Commerce Layer Provisioning API which means you would still be making API requests but with a different syntax. For now, we don't have comprehensive SDK documentation for every single resource our API supports, hence you will need to rely on our comprehensive Provisioning API Reference as you go about using this SDK. So for example, if you want to create a role, take a look at the Role object or the Create a role documentation to see the required attributes and/or relationships. The same goes for every other supported resource.
The code snippets below show how to use the SDK when performing the standard CRUD operations provided by our REST API. Kindly check our Provisioning API reference for the complete list of available resources and their attributes.
1 // Select the organization (it's a required relationship for the SKU resource) 2 const organizations = await clp.organizations.list({ filters: { name_eq: 'Test Org' } }) 3 4 const attributes = { 5 name: 'Test Role', 6 organization: clp.organizations.relationship(organizations.first().id), // assigns the relationship 7 } 8 9 const newRole = await clp.roles.create(attributes)
ℹ️ Check our API reference for more information on how to create a Role.
1 // Fetch the organization by ID 2 const org = await clp.organizations.retrieve('BxAkSVqKEn') 3 4 // Fetch all organizations and filter by name 5 const orgs = await clp.organizations.list({ filters: { name_start: 'TestOrg_' } }) 6 7 // Fetch the first organization of the list 8 const org = (await clp.organizations.list()).first() 9 10 // Fetch the last organization of the list 11 const org = (await clp.organizations.list()).last()
ℹ️ Check our API reference for more information on how to retrieve an organization.
1 // Fetch all the organizations 2 const orgs = await clp.organizations.list()
When fetching a collection of resources you can leverage the meta
attribute to get its meta
information like so:
1 const orgs = await clp.organizations.list() 2 const meta = orgs.meta
ℹ️ Check our API reference for more information on how to list all SKUs.
1 // Sort the results by creation date in ascending order (default) 2 const orgs = await clp.organizations.list({ sort: { created_at: 'asc' } }) 3 4 // Sort the results by creation date in descending order 5 const orgs = await clp.organizations.list({ sort: { created_at: 'desc' } })
ℹ️ Check our API reference for more information on how to sort results.
1 // Include an association (organization) 2 const mships = await clp.memberships.list({ include: [ 'organization' ] }) 3 4 // Include an association (stock role) 5 const mships = await clp.memberships.list({ include: [ 'role' ] })
ℹ️ Check our API reference for more information on how to include associations.
1 // Request the API to return only specific fields 2 const perms = await clp.permissions.list({ fields: { permissions: [ 'can_create', 'can_update' ] } }) 3 4 // Request the API to return only specific fields of the included resource 5 const mships = await clp.memberships.list({ include: [ 'organization' ], fields: { organizations: [ 'name' ] } })
ℹ️ Check our API reference for more information on how to use sparse fieldsets.
1 // Filter all the organizations fetching only the ones whose name starts with the string "ORG" 2 const orgs = await clp.organizations .list({ filters: { name_start: 'ORG' } }) 3 4 // Filter all the organizations fetching only the ones whose name ends with the string "Brand" 5 const orgs = await clp.organizations.list({ filters: { name_end: 'Brand' } }) 6 7 // Filter all the organizations fetching only the ones whose name contains the string "Test" 8 const orgs = await clp.organizations.list({ filters: { name_cont: 'Test' } }) 9 10 // Filter all the organizations fetching only the ones created between two specific dates 11 // (filters combined according to the AND logic) 12 const orgs = await clp.organizations.list({ filters: { created_at_gt: '2018-01-01', created_at_lt: '2018-01-31'} }) 13 14 // Filters all the organizations fetching only the ones created or updated after a specific date 15 // (attributes combined according to the OR logic) 16 const orgs = await clp.organizations.list({ filters: { updated_at_or_created_at_gt: '2019-10-10' } }) 17 18 // Filters all the Roles fetching only the ones whose name contains the string "Admin" 19 // and whose organization name starts with the string "ORG" 20 const roles = await clp.roles.list({ filters: { name_cont: 'Admin', organization_name_start: 'ORG'} })
ℹ️ Check our API reference for more information on how to filter data.
When you fetch a collection of resources, you get paginated results. You can request specific pages or items in a page like so:
1 // Fetch the organizations, setting the page number to 3 and the page size to 5 2 const skorgsus = await clp.organizations.list({ pageNumber: 3, pageSize: 5 }) 3 4 // Get the total number of organizations in the collection 5 const orgCount = orgs.meta.recordCount 6 7 // Get the total number of pages 8 const pageCount = orgs.meta.pageCount
PS: the default page number is 1, the default page size is 10, and the maximum page size allowed is 25.
ℹ️ Check our API reference for more information on how pagination works.
To execute a function for every item of a collection, use the map()
method like so:
1 // Fetch the whole list of organizations (1st page) and print their ids and names to console 2 const orgs = await clp.organizations.list() 3 orgs.map(o => console.log('ID: ' + o.id + ' - Name: ' + o.name))
Many resources have relationships with other resources and instead of including these associations as seen above, you can fetch them directly. This way, in the case of 1-to-N relationships, you can filter or sort the resulting collection as standard resources.
1// Fetch 1-to-1 related resource: billing address of an order 2const org = await clp.memberships.organization('xYZkjABcde') 3 4// Fetch 1-to-N related resources: orders associated to a customer 5const perms = await clp.roles.permissions('XyzKjAbCDe', { fields: ['can_create', 'can_update'] })
In general:
/api/organizations
or /api/organization/<organizationId>
translates to clp.organizations
or clp.organizations('<organizationId>')
with the SDK./api/roles/<roleId>/organization
translates to clp.roles('<roleId>', { include: ['organization'] }}
with the SDK./api/roles/<roleId>?include=versions
or /api/roles/<roleId>/permissions
translates to clp.roles.retrieve('<roleId>', { include: ['versions'] })
or clp.roles.permissions('<roleId>')
with the SDK.ℹ️ Check our API reference for more information on how to fetch relationships.
Many times you simply need to count how many resources exist with
certain characteristics. You can then call the special count
function passing a filter to get as result the total number of
resources.
1// Get the total number of sales_channel credentials 2const credentials = await clp.api_credentials.count({ filters: { kind_eq: 'sales_channel' } }) 3
1 const org = { 2 id: 'xYZkjABcde', 3 reference: '<new-reference>', 4 reference_origin: '<new-reference-origin>' 5 } 6 7 clp.organizations.update(org) // updates the SKU on the server
ℹ️ Check our API reference for more information on how to update an organization.
1 clp.memberships.delete('xYZkjABcde') // persisted deletion
ℹ️ Check our API reference for more information on how to delete a membership.
If needed, Commerce Layer Provisioning SDK lets you change the client configuration and 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:
1 // Permanently change configuration at client level 2 clp.config({ accessToken: 'your-access-token' }) 3 const roles = await clp.roles.list() 4 5 or 6 7 // Use configuration at request level 8 clp.roles.list({}, { accessToken: 'your-access-token' })
Commerce Layer Provisioning 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:
1 // Log error messages to console: 2 const attributes = { name: '' } 3 4 const newRole = await clp.roles.create(attributes).catch(error => console.log(error.errors)) 5 6 // Logged errors 7 /* 8 [ 9 { 10 title: "can't be blank", 11 detail: "name - can't be blank", 12 code: 'VALIDATION_ERROR', 13 source: { pointer: '/data/attributes/name' }, 14 status: '422', 15 meta: { error: 'blank' } 16 }, 17 { 18 title: "can't be blank", 19 detail: "organization - can't be blank", 20 code: 'VALIDATION_ERROR', 21 source: { pointer: '/data/relationships/organization' }, 22 status: '422', 23 meta: { error: 'blank' } 24 } 25 ] 26 */ 27
ℹ️ Check our API reference for more information about the errors returned by the API.
You can use interceptors to intercept SDK messages and modify them on the fly before the request is sent to the API or before the response is parsed and returned by the client. You can also access the error object before it is thrown by the SDK.
Interceptors are special functions that are able to handle SDK messages and return a (eventually) modified version of them for use by the client.
1 const requestInterceptor = (request: RequestObj): RequestObj => { 2 console.log(request) 3 return request 4 } 5 6 const responseInterceptor = (response: ResponseObj): ResponseObj => { 7 console.log(response) 8 return response 9 } 10 11 const errorInterceptor = (error: ErrorObj): ErrorObj => { 12 console.log(error) 13 return error 14 }
Here an example of how to use them:
1 // Add the interceptors (only one or all if needed) 2 clp.addRequestInterceptor(requestInterceptor) 3 clp.addResponseInterceptor(responseInterceptor, errorInterceptor) 4 5 const organizations = await clp.organizations.list() 6 7 // Remove interceptors 8 // Tt is possible to remove only a specific interceptor: cl.removeInterceptor('request') 9 cl.removeInterceptors()
The RawResponseReader is a special interceptor that allows to catch the original message coming frome the API before it is parsed and translated in SDK objects.
1 // Add a RawResponseReader capable of capturing also response headers 2 const rrr = clp.addRawResponseReader({ headers: true }) 3 4 const organizations = await clp.organizations.list() 5 6 cl.removeRawResponseReader() 7 8 console.log(rrr.rawResponse) 9 console.log(rrr.headers)
It is possible that you are using an access token that is about to expire especially if it has been used for many API calls. In this case you can define a special function that takes care of refreshing the token when a call fails because it has expired.
1 async function myRefreshTokenFunction(espiredToken: string): Promise<string> { 2 // Get a new access token using for example our js-auth library 3 return (await getAccessToken()).accessToken 4 } 5 6 cl.config({ refreshToken: myRefreshTokenFunction }) 7 8 // If needed you can later retrieve the new access token 9 const newToken = cl.currentAccessToken
Fork this repository (learn how to do this here).
Clone the forked repository like so:
1git clone https://github.com/<your username>/provisioning-sdk.git && cd provisioning-sdk
Make your changes and create a pull request (learn how to do this).
Someone will attend to your pull request and provide some feedback.
This repository is published under the MIT license.
No vulnerabilities found.
No security vulnerabilities found.