npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@commercelayer/provisioning-sdk

v2.0.2

Published

Commerce Layer Provisioning SDK

Downloads

1,711

Readme

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

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

  // 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.

  // 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.

  // 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.

  // 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.

  // 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.

  // 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.

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.

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

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.

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

  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

  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.