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

@gridscale/gsclient-js

v1.8.0

Published

gridscale API Wrapper

Downloads

786

Readme

npm version gridscale API 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/gsclient-js --save

or clone this repo and run

npm i
npm run 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/gsclient-js").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

global mode

By default, multiple client instances share token and settings. So if you create a new client instance, all the settings you apply there, will also be applied to all other instance. Even if you instanciate a new client instance with a different token, all the other instances will use the new token. This is due to historical reasonls.

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

isolated mode

The isolated mode behaves more common; each Client instance uses it's own settings. So you can have multiple instances with, for example, different tokens. Just set the 4th constructor property to true

Example

const client = new gridscale.Client("[API-Token]", "[User-UUID]", {}, true);
//                                                                    ^^^^

Filters

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