node package manager

tuTrabajo-client

tuTrabajo-client is a javascript client for use with tuTrabajo APIs.

TuTrabajo JS library

This is the TuTrabajo javascript client for use with tuTrabajo enabled APIs. It's written in javascript and tested with mocha, and is the fastest way to enable a javascript client to communicate with a tuTrabajo-enabled server.

Calling an API with tuTrabajo + node.js!

Install tuTrabajo-client:

npm install tuTrabajo-client

or:

bower install tuTrabajo-js

Then let tuTrabajo do the work!

var TuTrabajo = require('tuTrabajo-client');
 
 
 
```json
{
  "id": 1,
  "category": {
    "id": 2,
    "name": "Cats"
  },
  "name": "Cat 1",
  "photoUrls": [
    "url1",
    "url2"
  ],
  "tags": [
    {
      "id": 1,
      "name": "tag1"
    },
    {
      "id": 2,
      "name": "tag2"
    }
  ],
  "status": "available"
}

Need to pass an API key? Configure one in your client instance as a query string:

client.clientAuthorizations.add("apiKey", new TuTrabajo.ApiKeyAuthorization("api_key","special-key","query"));

...or with a header:

client.clientAuthorizations.add("apiKey", new TuTrabajo.ApiKeyAuthorization("api_key","special-key","header"));

...or with the tuTrabajo-client constructor:

var client = new TuTrabajo({
  url: 'http://example.com/spec.json',
  success: function() {},
  authorizations : {
    easyapi_basic: new TuTrabajo.PasswordAuthorization('<username>', '<password>'),
    someHeaderAuth: new TuTrabajo.ApiKeyAuthorization('<nameOfHeader>', '<value>', 'header'),
    someQueryAuth: new TuTrabajo.ApiKeyAuthorization('<nameOfQueryKey>', '<value>', 'query'),
    someCookieAuth: new TuTrabajo.CookieAuthorization('<cookie>'),
  }
});

Note the authorization nickname, such as easyapi_basic in the above example, must match the security requirement in the specification (see the OAI Specification for details).

You can also pass authorzations on a per-request basis, in the event that you're reusing a tuTrabajo-client object across multiple connections:

client.pet.addPet({pet: {
    name: 'doggie'
  }}, {
    clientAuthorizations: {
      api_key: new TuTrabajo.ApiKeyAuthorization('foo', 'bar', 'header')
    }
  })
  .then(function(pet) {
    console.log(pet.obj);
  });

Calling an API with tuTrabajo + the browser!

Download [browser/tuTrabajo-client.min.js](git url) and place it into your webapp:

<script src='browser/tuTrabajo-client.js' type='text/javascript'></script>
<script type="text/javascript">
  // initialize tuTrabajo client, point to a resource listing 
  window.client = new TuTrabajoClient({
    url: "http://tuTrabajo.com/prestadores.json",
    success: function() {
      // upon connect, fetch a pet and set contents to element "mydata" 
      client.prestadores.getPrestadorById({prestadorId:1},{responseContentType: 'application/json'}, function(data) {
        document.getElementById("mydata").innerHTML = JSON.stringify(data.obj);
      });
    }
  });
</script> 
 
<body>
  <div id="mydata"></div>
</body>

Need to send an object to your API via POST or PUT?

var pet = {
  id: 100,
  name: "dog"};
 
// note: the parameter for `addPet` is named `body` in the example below 
client.pet.addPet({body: pet});

Sending XML in as a payload to your API?

var pet = "<Pet><id>2</id><name>monster</name></Pet>";
 
client.pet.addPet({body: pet}, {requestContentType:"application/xml"});

Need XML response? (assuming your server can produce it)

client.pet.getPetById({petId:1}, {responseContentType:"application/xml"});

Custom request signing

You can easily write your own request signing code for TuTrabajo. For example:

var CustomRequestSigner = function(name) {
  this.name = name;
};
 
CustomRequestSigner.prototype.apply = function(obj, authorizations) {
  var hashFunction = this._btoa;
  var hash = hashFunction(obj.url);
 
  obj.headers["signature"] = hash;
  return true;
};

In the above simple example, we're creating a new request signer that simply Base64 encodes the URL. Of course you'd do something more sophisticated, but after encoding it, a header called signature is set before sending the request.

You can add it to the tuTrabajo-client like such:

client.clientAuthorizations.add('my-auth', new CustomRequestSigner());

Using your own HTTP client

Don't like superagent? Despise JQuery? Well, you're in luck. You can plug your own HTTP library easily:

var myHttpClient = {
  // implment an execute function 
  execute: function(obj) {
    var httpMethod = obj.method;
    var requestHeaders = obj.headers;
    var body = obj.body;
    var url = obj.url;
    // do your thing, and call `obj.on.response` 
    if(itWorked) {
      obj.on.response('horray');
    }
    else {
      obj.on.error('boo');
    }
  }
};
 
var client = new TuTrabajoClient({
  spec: petstoreRaw,
  client: myHttpClient,
  success: function () {
    client.pet.getPetById({petId: 3}, function(data){
      expect(data).toBe('ok');
      done();
    });
  }
});

How does it work?

The tuTrabajo javascript client reads the tuTrabajo api definition directly from the server. As it does, it constructs a client based on the api definition, which means it is completely dynamic. It even reads the api text descriptions (which are intended for humans!) and provides help if you need it:

s.apis.pet.getPetById.help()
'* petId (required) - ID of pet that needs to be fetched'

The HTTP requests themselves are handled by the excellent superagent library, which has a ton of features itself. But it runs on both node and the browser.

Development

Please fork the code

Note! We will not merge pull requests for features not supported in the OAI Specification! Add an issue there instead!

tuTrabajo-js use gulp for Node.js.

# Install the gulp client on the path
npm install -g gulp
 
# Install all project dependencies
npm install
# List all tasks.
gulp -T
 
# Run lint (will not fail if there are errors/warnings), tests (without coverage) and builds the browser binaries
gulp
 
# Run the test suite (without coverage)
gulp test
 
# Build the browser binaries (One for development with source maps and one that is minified and without source maps) in the browser directory
gulp build
 
# Continuously run the test suite:
gulp watch
 
# Run jshint report
gulp lint
 
# Run a coverage report based on running the unit tests
gulp coverage

License

Copyright 2016 SmartBear Software

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.