Giter Club home page Giter Club logo

chino-nodejs's Introduction

This repository is no longer maintained.

Chino.io Node JS client

Build Status codecov

Official Node JS wrapper for Chino.io APIs.

At the following links can be found:

Requirements

Before you can use Chino Node JS SDK you have to install Node JS Javascript runtime. If you haven't it yet, you can follow the instructions provided on Node JS website.

Installation

To install Chino SDK in your Node JS project you can run the following command

npm install --save chinoio

The above command will download Chino SDK in your node_modules directory and will add the dependency in your package.json file.

Test the SDK

Once requirements are satisfied you can test the SDK. In order to complete this task you have to follow these steps:

Clone this repository with the following command:

git clone https://github.com/danibix95/chino-nodejs.git

Then go inside the repository folder:

cd chino-nodejs

And install project dependencies:

npm install

After the install process, open /test/testSettings.js file and insert base url for calls (e.g. the one for testing if you have a free plan), your Chino customer id and customer key:

Inside file /test/testSettings.js

...
module.exports.baseUrl = "https://api.test.chino.io/v1";
module.exports.customerId  = "your-Chino-Customer-ID";
module.exports.customerKey = "your-Chino-Customer-KEY";
...

Now the project is ready to be tested. Run the following command to test it:

npm test

SDK Usage

First steps

After you have installed the SDK you can import it in your project and create the main object:

const Chino = require("chino-sdk");     // before working, SDK have to publish
                                        // on NPM and installed locally

const chinoClient = new Chino("base-url", "chino-id", "chino-key");

Parameters used for construct a Chino object are:

  • base-url
    the url at which the client will makes requests
    e.g. https://api.test.chino.io/v1
    Please, notice that there is no slash at end of the URL.
  • chino-id
    the Chino customer id that you own
  • chino-key
    one of the Chino customer key associated with your account

Note: creating a client in this way is meant for development or for authentication purpose, since this grant to client no restriction on call permissions.

Now we have a client object. Let's us make a call to Chino APIs. For example we create a repository on Chino, using as parameter the right object (according to Chino API docs):

const data = {
    description: "This is a test repository"
}

chinoClient.repositories.create(data);

Set Chino credentials for application user

OK, we created a Chino client for a developer. Now we will follow these basic steps to set up a client for an application user. This client will be limited by user Chino permissions (see docs for further information on permissions).

First of all we need to create a Chino Application and set its credentials (application id and application secret). These properties are kept private for security reasons.

const appData = {
    grant_type: "password",
    name: "Application test"
}

chinoClient.applications.create(appData)
    .then((app) => {
        // enable chino client to authenticate application users 
        chinoClient.setAuth(app.app_id, app.app_secret);
    })
    .catch((error) => {
        // manage request error
        console.log(error);
    });

Then you can authenticate a user and retrieve an access token, that will be used later for accessing Chino API (Attention: the access token has an expiration, see docs for managing it).

 let token = "";
 
 chinoClient.auth.login(username, password)
    .then((auth) => {
        token = auth.access_token;
    })

Now that we have a token, we can create a client for an application user:

const userClient = new Chino("base-url", token);

This time, Chino constructor parameters are:

  • base-url
    see above for description
  • token this is the user access token we retrieved before. It is used to identify user calls.

In the end we can try to make a call as user application:

userClient.users.current()
    .then((user) => {
        // show current user details
        console.log(user);
    }
    .catch((error) => {
        // manage request error
    }

Notes

Since requesting to REST service could require some time, each call is made asynchronously. As a result, each function return a Promise object that will be resolved if client receive a 200 (OK) status code as response from server, otherwise it will be rejected.

Moreover, if you have to make sequential calls, you have to chain returned promises from each call.

Examples

For further information view SDK docs. You can view an example of application in the example branch.

License

MIT

chino-nodejs's People

Contributors

danibix95 avatar zidia avatar

Stargazers

 avatar

Watchers

 avatar  avatar

chino-nodejs's Issues

Improve documentation

I should add a description to function's parameters, to classes' properties and to constants.

Permission lib can be improved

Permission methods have too much parameters. To simplify the parameters' passage, it could be useful to pass only a single object with correct properties.

Response piping blob data doesn't work

Issue: when I try download to blob data after I uploaded it I'm not able to write blob on a file.

I've tried in different ways:

  • writing directly to file response.data content (binary data)
  • piping response stream to a writable stream without any library
  • piping response stream to a writable stream with through2 lib (see below)
  • listen on any of writable stream and response event to try get something. The only one fired (once) was pipe

The test results always in timeout exceed because it seems that response never fire any events (overall the end event).

To reproduce the issue clone the repository, change branch to dev, install node packages and test it.

git clone https://github.com/danibix95/chino-nodejs.git
git checkout dev
npm install
./node_modules/mocha/bin/mocha test/lib/blobsTest.js

NOTE: need to set up test settings file in test/testSetting.js changing Chino ID & Key. Then go to your chino console create a repository and paste its id in test/lib/blobsTest.js at line 29.

Blob download function (src/blobs.js)

const fs = require("fs");
const through2 = require("through2");
const objects = require("./objects");

download(blobId, newFileName = "") {
    function doDownload(resolve, reject) {
      this.call.getBlob(`/blobs/${blobId}`, {})
          .then((response) => {
            const fileName = newFileName ||
                             response.header["content-disposition"].split("=")[1].trim();

            // console.log(response) => return the right response that contain binary data 

            response
                .pipe(through2(function (chunk, enc, callback) {
                    //Here is never reched
                    console.log("Chunking")
                    this.push(chunk)
                }))
                // the file is created each time, but it's always empty
                .pipe(fs.createWriteStream(fileName))
                .on("finish", function () {
                    // As same as above we never reach this line
                    console.log("I've finish")
                    const ok = {
                      result_code: 200,
                      result: "success",
                      data : null,
                      message : null
                    };
                    resolve(new objects.Success(ok));
                })
          })
          .catch((error) => { reject(new objects.ChinoError(error)) });
    }

    return new Promise(doDownload.bind(this));
}

Function used to retrieve blob data (src/apiCall.js)

const request = require("superagent");
const binaryParser = require("superagent-binary-parser");

getBlob(url, params = {}) {
    let makeCall = (resolve, reject) => {
      function blobResponseHandler(error, response) {
        if (error) {
          reject(response || error);
        }
        else {
          resolve(response);
        }
      }

      request
          .get(this.baseUrl + url)
          .auth(_(this).id, _(this).secret)
          .type("application/json")
          .accept("application/octet-stream")
          .query(params)
          .buffer(true)
          .parse(binaryParser)
          .end(blobResponseHandler);
    }

    return new Promise(makeCall);
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.