Search code examples
cumulocity

How use the @c8y/client library


I am testing the new @c8y/client library for typescript.

I have a very simple code :

import {
  Client
} from '@c8y/client';
//const baseUrl = 'https://bismark1.cumulocity.com/';
const baseUrl = 'https://demos.cumulocity.com/';
const tenant = 'bismark1';
const user = '...';
const password = '.....';


(async() => {
  console.log('authentication to c8y server')
  const client = await Client.authenticate({
    user,
    password,
    tenant
  }, baseUrl);

  console.log('result from authetication', client)
  const {
    data,
    paging
  } = await client.inventory.list();
  console.log('result from inventory ', data)

  // data = first page of inventory
  const nextPage = await paging.next();
  // nextPage.data = second page of inventory

  const managedObjId: number = 1;

  (async() => {
    const {
      data,
      res
    } = await client.inventory.detail(managedObjId);
    console.log(data)
  })();

})();

When I run the .js compiled form the .ts file I get the response below :

authentication to c8y server

And then the execution stops.

The line

console.log('result from authetication', client)

is never called. Seems like something fails in the authentication process and not error is showed.

What I'm doing wrong ?

Thanks.


Solution

  • The first problem might be CORS. You need to enable it if you want to request from a different domain. Here is a guide how to do that in Cumulocity:

    Under "Access control", administrators can enable cross-origin resource sharing or "CORS" on the Cumulocity API.

    The second problem could be that you are not running it from a local development server. I mostly use this http-server from npm to quickly test scripts. You can use it the following way:

    $ npm install http-server -g
    $ http-server
    

    If that all is not helping you might try catch the client to see the error it is throwing:

    try {
      const client = await Client.authenticate({
        user,
        password,
        tenant
      }, baseUrl);
    } catch(ex) {
     console.log(ex);
    }
    

    The exeption might tell you more about what is wrong with your code or if there is a bug in the client.