A Deno SDK for commercetools

A Deno SDK for commercetools

Willem Haring
Willem Haring
Sales Engineer, commercetools
Published 15 November 2023
Estimated reading time minutes

The Deno runtime is ideal to quickly run experiments with and allows you to run small pieces of code without overhead. In a pre-sales function, it is an ideal environment to create small pieces of demonstration code. In this article, I explain why I created the Deno SDK, how I created it, what my challenges were, how they disappeared overtime and how you can use the SDK.

A Deno SDK for commercetools

How it all started

When I started at commercetools in March 2022, I had to brush up my Javascript and TypeScript skills quite a bit after two and a half years of working in the low-code space. So I started reading. And experimenting. I installed node on my brand-new laptop and, before I knew it, my dev folder was cluttered with gigantic modules folders. Until I watched this video:

From this video, I learned that Ryan was working on a new Javascript runtime. Not only does it run TypeScript without the need to configure a compiler, it also has support for some standard libraries. See the following video for a short introduction:

The third slide in the video captures why I got interested:

"I want a fun and productive system for scripting. A good scripting platform is too useful of a tool to shrug and accept the status quo."

And there is a good reason for it: Doing a demo of a headless commerce system with Postman sometimes feels like selling a bike to a car dealer.

So, from there I started. In July 2022 Deno was working fine, but it had its limitations. There wasn't support for NPM modules at all, but you could run TypeScript. So I downloaded the commercetools TypeScript SDK and the SDK platform from Github and gave it a go. It did not work. Deno expects .ts extensions on the file imports. So, I renamed all my includes and gave it another try. Still no good. I got an error on fetch. Then, I replaced it with the Deno native fetch. Boom. Working.

For the next couple of weeks in my downtime hours, I did more experiments and figured out that I could also deploy my Deno code to Deno. After a couple of more experiments, my first commercetools API extension was running! I then did a couple of demos with it and all yielded positive responses. And I thought, "wow." Now, I can very quickly write some scripts and actually use them in a very scalable, repeatable and shareable way.

Deno is growing up: NPM support

Then, as things go in life and work, I had to focus on other things. But I kept on reading the Deno release notes and I noticed that NPM support was introduced. At first, I tried including the commercetools SDK, but no luck. But with a later release it actually worked, which led me to pick it up again.

The first thing I wanted to do was to make things as simple as possible. My goal was to get some working samples running ASAP. So I needed a very lightweight setup: Just a copy of a .env file, fresh from the Merchant Center’s developer settings:

deno client

All the SDK needs is the information from the .env file to work. So, save the .env file to a new folder on your hard drive. Deno has standard support for reading .env files:

import { config as dotEnvConfig } from 'https://deno.land/x/dotenv@v1.0.1/mod.ts'

export interface iConfig
{
   project_key: string
   client_secret: string
   client_id: string
   auth_url: string
   api_url: string
}

dotEnvConfig({ export: true})
const config: iConfig = {
   api_url: Deno.env.get('CTP_API_URL')! ,
   auth_url: Deno.env.get('CTP_AUTH_URL')!,
   project_key: Deno.env.get('CTP_PROJECT_KEY')!,
   client_id: Deno.env.get('CTP_CLIENT_ID')!,
   client_secret: Deno.env.get('CTP_CLIENT_SECRET')!,
}

console.log(config)

Copy the lines above in a file called config.ts in the same folder where you saved the .env file.

The first line in the example loads a Deno module directly from a URL — no need to specify anything in a package.json file! Deno caches the modules it loads in a shared cache folder.

One other thing that Deno does really well are security checks. So make sure you have Deno installed on your machine: instructions. And run the config file like this from the folder where you saved it.

deno run config.ts

Deno will try to read from a .env file and will ask the user for permission:

⚠️ Deno requests read access to ".env".
├ Requested by `Deno.readFileSync()` API.
├ Run again with - allow-read to bypass this prompt.
└ Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all read permissions)

It does this for not only for reading the file, but also for each environment variable:

⚠️ Deno requests env access to "CTP_PROJECT_KEY".
├ Run again with - allow-env to bypass this prompt.
└ Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all env permissions)

When all permissions are given, this should be the result:

deno run config.ts
✅ Granted read access to ".env".
✅ Granted read access to ".env.defaults".
✅ Granted env access to "CTP_PROJECT_KEY".
✅ Granted env access to "CTP_CLIENT_SECRET".
✅ Granted env access to "CTP_CLIENT_ID".
✅ Granted env access to "CTP_AUTH_URL".
✅ Granted env access to "CTP_API_URL".
✅ Granted env access to "CTP_SCOPES".
{
   api_url: "https://api.europe-west1.gcp.commercetools.com",
   auth_url: "https://auth.europe-west1.gcp.commercetools.com",
   project_key: "**-****-******",
   client_id: "**** ****** ****** ******",
   client_secret: "******* **** *** **** ****"
}

With the support for NPM in Deno, including the commercetools typescript SDK’s can be done like this:

import { ClientBuilder } from "npm:@commercetools/sdk-client-v2"
import { ApiRoot, createApiBuilderFromCtpClient } from "npm:@commercetools/platform-sdk"

A Deno SDK for commercetools

With this, I started building an SDK client that needs only the following on my file system:

.env
project.ts

This is a file that I can execute immediately after downloading or after creation from scratch. No more NPM installs that fail. No more cluttered hard drives. No more struggling with TypeScript compiler options.

My very simple sample code in project.ts:

import {sdk} from "https://deno.land/x/commercetools_demo_sdk/clientsdk.ts";

const handle = sdk.init()
const result = await handle
   .root()
   .get()
   .execute()
console.log(result.body)

Run with:

deno run -A project.ts

Step by step:

  • The -A gives an allow-all consent on the security questions.
  • The first line loads the SDK from the deno module repository.
  • sdk.init() loads the .env file and loads the platform SDK.
  • With the handle variable you can call the commercetools root() object, to start your command structure.
  • Same as with the TypeScript SDK, doing a get().execute() on the project will get you a project response.
  • The result.body contains the details of the project!

Some hints and tips:

  1. Install the vscode deno extension

  2. In your vscode workspace run: deno.initializeWorkspaceConfiguration

Now syntax highlighting works like a charm and vscode does not mix up Deno code with Node code.

Using the SDK

There are a couple of really handy and nice things to build into Deno. For instance, you can run a Deno script that is deployed remotely. Just give it a try:

deno run -A https://deno.land/x/commercetools_demo_sdk/projectsample.ts

This will execute the code directly from the repository. All it needs is a .env file in the folder where you are executing from!

And even better, you can also install the remote script as an executable command!

deno install -A https://deno.land/x/commercetools_demo_sdk/projectsample.ts

You can now run:

projectsample

In the next article, I will leverage the API to seamlessly import customers, taking advantage of its integration with the commercetools import API.

Willem Haring
Willem Haring
Sales Engineer, commercetools

Willem has been working in retail technology since the beginning of 2000. He has worked with several technology companies and with clients on point of sales, stores infrastructure, reporting and dashboarding. He has been a participating member on the ARTS committee for the data warehouse chapter under ARTS XML. At commercetools, Willem works with clients, prospects and customers to translate complicated use cases to workable eCommerce solutions based on commercetools.

Latest Blog Posts