@commercelayer/provisioning-sdk
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

Commerce Layer Provisioning SDK

Version Downloads/week License semantic-release: angular Release CodeQL TypeScript

A JavaScript Library wrapper that makes it quick and easy to interact with the Commerce Layer Provisioning API.

Table of contents


Getting started

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.

Installation

Commerce Layer Provisioning SDK is available as an npm and yarn package that you can install with the command below:

npm install @commercelayer/provisioning-sdk

// or

yarn add @commercelayer/provisioning-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. Kindly check our documentation for more information about the available authorization flows.

Feel free to use Commerce Layer Provisioning Auth, a JavaScript library that helps you wrap our authentication API.

Import

You can use the ES6 default import with the SDK like so:

import CommerceLayerProvisioning from '@commercelayer/provisioning-sdk'

const clp = CommerceLayerProvisioning({
  accessToken: 'your-access-token'
})

SDK usage

The JavaScript 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.

Create

How to create a Role
  // Select the organization (it's a required relationship for the SKU resource)
  const organizations = await clp.organizations.list({ filters: { name_eq: 'Test Org' } })

  const attributes = {
    name: 'Test Role',
    organization: clp.organizations.relationship(organizations.first().id), // assigns the relationship
  }

  const newRole = await clp.roles.create(attributes)

ℹ️ Check our API reference for more information on how to create a Role.

Retrieve / List

How to fetch a single organization
  // Fetch the organization by ID
  const org = await clp.organizations.retrieve('BxAkSVqKEn')

  // Fetch all organizations and filter by name
  const orgs = await clp.organizations.list({ filters: { name_start: 'TestOrg_' } })

  // Fetch the first organization of the list
  const org = (await clp.organizations.list()).first()

  // Fetch the last organization of the list
  const org = (await clp.organizations.list()).last()

ℹ️ Check our API reference for more information on how to retrieve an organization.

How to fetch a collection of organizations
  // Fetch all the organizations
  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:

  const orgs = await clp.organizations.list()
  const meta = orgs.meta

ℹ️ Check our API reference for more information on how to list all SKUs.

How to fetch a collection of organizations and sort the results
  // Sort the results by creation date in ascending order (default)
  const orgs = await clp.organizations.list({ sort: { created_at: 'asc' } })

  // Sort the results by creation date in descending order
  const orgs = await clp.organizations.list({ sort: { created_at: 'desc' } })

ℹ️ Check our API reference for more information on how to sort results.

How to fetch a collection of Memberships and include associations
  // Include an association (organization)
  const mships = await clp.memberships.list({ include: [ 'organization' ] })

  // Include an association (stock role)
  const mships = await clp.memberships.list({ include: [ 'role' ] })

ℹ️ Check our API reference for more information on how to include associations.

How to fetch a collection of Permissions and return specific fields (sparse fieldsets)
  // Request the API to return only specific fields
  const perms = await clp.permissions.list({ fields: { permissions: [ 'can_create', 'can_update' ] } })

  // Request the API to return only specific fields of the included resource
  const mships = await clp.memberships.list({ include: [ 'organization' ], fields: { organizations: [ 'name' ] } })

ℹ️ Check our API reference for more information on how to use sparse fieldsets.

How to fetch a collection of organizations and filter data
  // Filter all the organizations fetching only the ones whose name starts with the string "ORG"
  const orgs = await clp.organizations .list({ filters: { name_start: 'ORG' } })

  // Filter all the organizations fetching only the ones whose name ends with the string "Brand"
  const orgs = await clp.organizations.list({ filters: { name_end: 'Brand' } })

  // Filter all the organizations fetching only the ones whose name contains the string "Test"
  const orgs = await clp.organizations.list({ filters: { name_cont: 'Test' } })

  // Filter all the organizations fetching only the ones created between two specific dates
  // (filters combined according to the AND logic)
  const orgs = await clp.organizations.list({ filters: { created_at_gt: '2018-01-01', created_at_lt: '2018-01-31'} })

  // Filters all the organizations fetching only the ones created or updated after a specific date
  // (attributes combined according to the OR logic)
  const orgs = await clp.organizations.list({ filters: { updated_at_or_created_at_gt: '2019-10-10' } })

  // Filters all the Roles fetching only the ones whose name contains the string "Admin"
  // and whose organization name starts with the string "ORG"
  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.

How to paginate a collection of organizations

When you fetch a collection of resources, you get paginated results. You can request specific pages or items in a page like so:

  // Fetch the organizations, setting the page number to 3 and the page size to 5
  const skorgsus = await clp.organizations.list({ pageNumber: 3, pageSize: 5 })

  // Get the total number of organizations in the collection
  const orgCount = orgs.meta.recordCount

  // Get the total number of pages
  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.

How to iterate through a collection of Organizations

To execute a function for every item of a collection, use the map() method like so:

  // Fetch the whole list of organizations (1st page) and print their ids and names to console
  const orgs = await clp.organizations.list()
  orgs.map(o => console.log('ID: ' + o.id + ' - Name: ' + o.name))
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. This way, in the case of 1-to-N relationships, you can filter or sort the resulting collection as standard resources.

// Fetch 1-to-1 related resource: billing address of an order
const org = clp.memberships.organization('xYZkjABcde')

// Fetch 1-to-N related resources: orders associated to a customer
const perms = clp.roles.permissions('XyzKjAbCDe', { fields: ['can_create', 'can_update'] })

In general:

  • An API endpoint like /api/organizations or /api/organization/<organizationId> translates to clp.organizations or clp.organizations('<organizationId>') with the SDK.
  • 1-to-1 relationship API endpoints like /api/roles/<roleId>/organization translates to clp.roles('<roleId>', { include: ['organization'] }} with the SDK.
  • 1-to-N relationship API endpoints like /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.

How to count resources

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.

// Get the total number of sales_channel credentials
const credentials = clp.api_credentials.count({ filters: { kind_eq: 'sales_channel' } })

Update

How to update an existing organization
  const org = {
    id: 'xYZkjABcde',
    reference: '<new-reference>',
    reference_origin: '<new-reference-origin>'
  }

  clp.organizations.update(org) // updates the SKU on the server

ℹ️ Check our API reference for more information on how to update an organization.

Delete

How to delete an existing membership
  clp.memberships.delete('xYZkjABcde') // persisted deletion

ℹ️ Check our API reference for more information on how to delete a membership.

Overriding credentials

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:

  // Permanently change configuration at client level
  clp.config({ accessToken: 'your-access-token' })
  const roles = await clp.roles.list()

  or

  // Use configuration at request level
  clp.roles.list({}, { accessToken: 'your-access-token' })

Handling validation errors

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:

  // Log error messages to console:
  const attributes = { name: '' }

  const newRole = await clp.roles.create(attributes).catch(error => console.log(error.errors))

  // Logged errors
  /*
  [
    {
      title: "can't be blank",
      detail: "name - can't be blank",
      code: 'VALIDATION_ERROR',
      source: { pointer: '/data/attributes/name' },
      status: '422',
      meta: { error: 'blank' }
    },
    {
      title: "can't be blank",
      detail: "organization - can't be blank",
      code: 'VALIDATION_ERROR',
      source: { pointer: '/data/relationships/organization' },
      status: '422',
      meta: { error: 'blank' }
    }
  ]
  */

ℹ️ Check our API reference for more information about the errors returned by the API.

Contributors guide

  1. Fork this repository (learn how to do this here).

  2. Clone the forked repository like so:

    git clone https://github.com/<your username>/provisioning-sdk.git && cd provisioning-sdk
  3. Make your changes and create a pull request (learn how to do this).

  4. Someone will attend to your pull request and provide some feedback.

Need help?

  1. Join Commerce Layer's Slack community.

  2. Create an issue in this repository.

  3. Ping us on Twitter.

License

This repository is published under the MIT license.

Package Sidebar

Install

npm i @commercelayer/provisioning-sdk

Weekly Downloads

261

Version

2.0.0

License

MIT

Unpacked Size

155 kB

Total Files

7

Last publish

Collaborators

  • commercelayer.io
  • drpierlu