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

@c8y/client

v1019.24.1

Published

Client application programming interface to access the Cumulocity IoT-Platform REST services.

Downloads

13,987

Readme

@c8y/client

The @c8y/client is an isomorphic (node and browser) Javascript client library for the Cumulocity IoT platform API.

Installation

npm install @c8y/client

Usage

Use client.<endpoint>.list() to request listed data from the Cumulocity REST API and client.<endpoint>.detail(<id>) to request detail information. These methods always return a promise.

In the following sections, the default signature of these functions is described. For detailed information, refer to the complete documentation).

Get detail and list data with promises (pull)

| Method | Description | Parameters | Return | | --- | --- | --- | --- | | detail(entityOrId) | Request detail data of a specific entity. | entityOrId: string | number | IIdentified: An object which contains an id or an id as number or string. | Promise<IResult<TData>>: The list as Promise wrapped in an IResult. IResultList contains data and response. | | list(filter) | Request a list of data with an optional filter. | filter:object: (optional) A filter for paging or filtering of the list. | Promise<IResultList<TData>>: The list as Promise wrapped in an IResultList. IResultList contains data, response and paging. |

  • Example for receiving details of one managed object of the inventory via detail:

     const managedObjId: number = 1;
    
     (async () => {
       const {data, res} = await client.inventory.detail(managedObjId);
     })();
  • Example for receiving a list of one managed object of the inventory via list:

     const filter: object = {
       pageSize: 100,
       withTotalPages: true
     };
    
     (async () => {
       const {data, res, paging} = await client.inventory.list(filter);
     })();

Accessing a microservice with the Fetch API

The client internally uses the Fetch API. By accessing this core function, you can do any authenticated request to any resource. Standalone you can use core.client.fetch(url, options) and in @c8y/ngx-components/data for Angular you simply need to inject the FetchClient:

constructor(private fetchClient: FetchClient) {} // di

async getData() {
  const options: IFetchOptions = {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    };
  const response = await this.fetchClient.fetch('/service/my-service', options); // Fetch API Response
}

All fetch responses with application/json content type can be parsed to JSON objects. Find more information on handling fetch responses in the MDN documentation.

Authentication strategy

In the Cumulocity platform we currently allow two ways to authenticate:

  • Basic Auth: The authentication header (Basic) is injected into each request.
  • OAI (via cookie): The client doesn't know about the authentication header. The header is set in a cookie.
  • OAI (via token): The client requests a token. An authentication header (Bearer) is injected into each request.

To quickly get you started, the @c8y/client provides a shorthand static function which always uses Basic Auth and verifies the login directly:

await Client.authenticate({ tenant, user, password }, url);

It internally creates a client instance and tries to contact the API to verify if the given credentials are correct. In some cases you need to use a more fine-grained authentication, e.g. when you don't know which authentication strategy the user is going to use. In this case you need to construct an own instance of the client and pass the authentication strategy to it:

 const baseUrl = 'https://acme.cumulocity.com';
 const client = new Client(new CookieAuth(), baseUrl); // use here `new BasicAuth()` to switch to Basic Auth
 try {
  const { data, paging, res } = await client.user.currentUser();
  console.log('Login with cookie successful');
 } catch(ex) {
  console.log('Login failed: ', ex)
 }

Note: As the default login mode for UI is OAI, you usually don't need to authenticate via Basic Auth.

To login via OAI and use a Cookie for authentication you can use:

const client = await Client.getOAuthInternalClientViaCookie({ tenant, user, password }, url);

To login via OAI and use the authentication header for authentication you can use:

const client = await Client.authenticateViaOAuthInternal({ tenant, user, password }, url);

Examples

Below some examples are provided which may help you to get started. To see a complex and full implementation of the client into Angular, have a look at @c8y/cli and the new command to spin up a example application for Angular.

Requesting list data from the inventory:

import { Client } from '@c8y/client';

const baseUrl = 'https://demos.cumulocity.com/';
const tenant = 'demos';
const user = 'user';
const password = 'pw';

(async () => {
  const client = await Client.authenticate({
    tenant,
    user,
    password
  }, baseUrl);
  const { data, paging } = await client.inventory.list();
  // data = first page of inventory
  const nextPage = await paging.next();
  // nextPage.data = second page of inventory
})();

Using realtime:

// realtime event
const subscription = client.realtime.subscribe('/alarms/*', (data) => {
  console.log(data); // logs all alarm CRUD changes
});
client.realtime.unsubscribe(subscription);

Authenticate in node.js

The constructor new Client([...]) initializes a new Client which allows to request data from the API. Differently to Client.authenticate([...]) it needs a tenant given and does not verify if the login is correct. This is useful if you are developing a node.js microservice.

const auth = new BasicAuth({ 
   user: 'youruser',
   password: 'yourpassword',
   tenant: 'acme'
 });

 const baseUrl = 'https://acme.cumulocity.com';
 const client = new Client(auth, baseUrl);
 (async () => {
   const { data, paging, res } =  await client.inventory.list({ pageSize: 100 });
 })();