This package has been deprecated

Author message:

WARNING: This project has been renamed to @gridscale/gsclient-js. Please install using our new package name instead.

@gridscale/api
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

npm version

gridscale JavaScript client library

This is the JavaScript library for our public API. We developed this package for our Panels and want to share it with you.

Prerequisites

To be able to use this client, a number of steps need to be taken. First a gridscale account will be required, which can be created here. Then an API-token should be created.

Installation

Install the package by npm running

npm i @gridscale/api --save

or clone this repo and run

npm i
npm build

This will build the client into the dist directory.

Using the client

In a browser

After installing, generate the library for browsers by running

npm run build-browser

This will create the dist/client.js file which you will need.

Then in your HTML you use

  <html>
  <head>
    <meta charset="utf-8" />
    <script type="text/javascript" src="client.js"></script>
  </head>
  <body>...</body>
  <script type="text/javascript">
    var client = new gridscale.Client('[API-Token]', '[User-UUID]')
    //client.Server.list()...
    </script>
  </html>

In Node.js

const gridscale = require("@gridscale/api").gridscale;
const client = new gridscale.Client("[API-Token]", "[User-UUID]");

API Documentation

For details to all API endpoints and their methods, you should refer to the official API documentation here - https://gridscale.io/en/api-documentation/index.html

Demo

Test basic functionality in our Demo

Types & Schemas

Since version 1.0.0 the typescript type definitions of all API parameters and responses are bundled with this package. Developer note: This client is not (yet) automatically updated on changes to the gridscale public API. To update the types from the official API spec, run npm run updateFromSpec.

There are also additional schemas bundled with this package, containing additional formatting hints on the types (e.g. special string formats etc.). The schemas are named like the types, prefixed by a $.

Example:

import { ServerCreate, $ServerCreate }

const createServerForm: ServerCreate = {
  name: "test",
  cores: 1,
  memory: 1
};

onUserInput(formData) {
  // @TODO: perform additional user input checking
  console.log($ServerCreate.properties);
  /*
  {
    name: {
        type: 'string',
        isRequired: true,
    },
    cores: {
        type: 'number',
        isRequired: true,
    },
    memory: {
        type: 'number',
        isRequired: true,
    },
    labels: {
        type: 'array',
        contains: {
            type: 'string',
        },
    },
    status: {
        type: 'string',
    },
    availability_zone: {
        type: 'string',
    },
    auto_recovery: {
        type: 'string',
    },
    hardware_profile: {
        type: 'Enum',
    },
  }
  */
}

Client settings

Global options

You can set global options, which apply on every object type when creating the client. The third parameter of the constructor can be used for options

Example

const client = new gridscale.Client("[API-Token]", "[User-UUID]", {
  limit: 25, // Default page-size for list response
  watchdelay: 100, // Delay between the single requests when watching a job (RequestID)
});

You can also set the options only for specific object types by using the setDefaults function for an object. This will override the global settings

Example

client.Server.setDefaults({
    page  : 0,    // Index of Page
    limit : 25,   // Number of Objects per page
    offset: 0,    // Offset from start,
    sort  : [-name,+object_uuid], // Sort by fileds
    fields : [name,object_uuid,...], // Fields that should get included into the Response
    filter : [name='name',capacity<=30] //  Only return data that matches the filter
});

You can also set the options for a single request to filter your objects. This will override global and per-object-type settings

Example

client.Server.list({
  page: 0,
  limit: 10,
  sort: "name",
  fields: ["name", "object_uuid"],
  filter: ["memory>16"],
}).then(_callback);

In this example the result will be the first 10 servers with more then 16GB of memory. Sorted by name and only returning the name and the object_uuid.

Available filter operators:

Here you find an overview of the filter operators available when using the filter option.

"=" String or value comparison: exact match
"<>" String or value comparison: does not match
"<" Value less than
">" Value greater than
"<=" Value less or equal
">=" Value greater or equal

Callback Functions and Promises

All requests and actions for the objects return a Promise. You are also free to use a callback style for each action. The last parameter of each method accepts a callback function. Both, Promise and callback receive the same result object that gets passed to the function

Example with Promise

client.Server.list().then(
  function (result) {
    // do something when the request succeeded. result is the result object described below
    console.log(result);
  },
  (error) => {
    // handle when the request is failed, error.result contains the result object described below
    console.error(error.result);
  }
);

Example with callback

client.Server.list({}, (response, result) => {
  // for historical reasons, the callbacks first parameter is the raw Response from Javascript fetch(), second parameter is the result object described below

  if (result.success) {
    // do something when the request succeeded. result is the result object described below
    console.log(result);
  } else {
    // handle when the request is failed, error.result contains the result object described below
    console.error(result);
  }
});

Asynchronous requests

Some requests are processed in an aynchronous way, meaning that sending the requests starts a job in the background. The request returns (with HTTP Code 202 - Accepted) but the operation itself may not be finished. This requests return a X-Request-Id header, which corresponds to the background job and allows querying the status by sending this ID to the /request endpoint.

Watching asynchronous request with the client

When a client method starts an asynchronous request, the response object contains a watch property, which is a function which - once called - will start watching the background job your request just started (for example creating a large storage). The Promise that is returned by the watch-function will get resolved when the background job is done, or rejected when the job failed in the background.

Example

// Creating a new Storage with 1TB Size
client.Storage.create({
  name: "Storage1",
  capacity: 1024,
  location_uuid: "39a7d783-3873-4b2f-915b-4c86c28344e5",
}).then(function (_result) {
  console.log(
    "Storage with UUID: " + _result.result.object_uuid + " is provisioning..."
  );

  // Watching the Storage until it is ready to work with
  _result.watch().then(function () {
    console.log("Storage is ready to use!");
  })
  .catch(e => {
    console.error('Provisioning the storage failed', e));
  });
});

You can also directly query a job status with a request-ID (X-Request-Id header) by using

client.watchRequest( "[x-request-uuid]" ).then(function () {
  console.log("Storage is ready to use!");
})
.catch(e => {
  console.error('Provisioning the storage failed', e));
});

Global error handling

While you can handle errors per request by handling rejected promises or checking the success property of the result in callbacks, you can also set a global error handler for the API.

To do that you register a handler function with the addLogger method of the API client. You can also register more handlers by multiple calling addLogger. All your error handlers will get executed on each error.

Example

const client = new gridscale.Client(API - Token, User - UUID);

client.addLogger((error) => {
  // error object described below
  console.error("API ERROR OCCURED", error.id, error.result);
});

Package Sidebar

Install

npm i @gridscale/api

Homepage

gridscale.io

Weekly Downloads

68

Version

1.0.3

License

ISC

Unpacked Size

2 MB

Total Files

1877

Last publish

Collaborators

  • janstuhlmann
  • marcd
  • tbrandenberg