Skip to content

holidayextras/jsonapi-client

Repository files navigation

Coverage Status Build Status Code Climate Codacy Badge Dependencies Status

jsonapi-client

A javascript module designed to make it really easy to consume a json:api service.

** ⚠ !! THIS PROJECT IS IN NPM AS @holidayextras/jsonapi-client !! **

$ npm install --save @holidayextras/jsonapi-client

note: this project requires a Node.js version of at least 4.5.0.

Motivation / Justification / Rationale

Consuming a json:api service from within Javascript is a non-trivial affair. Setting up a transport mechanism, authentication, making requests to standardised HTTP routes, error handling, pagination and expanding an inclusion tree... All of these things represent barriers to consuming an API. This module takes away all the hassle and lets developers focus on interacting with a rich API without wasting developer time focusing on anything other than shipping valuable features.

This module is tested against the example json:api server provided by jsonapi-server.

Full documentation

The tl;dr

In a browser

<script src="/dist/jsonapi-client.min.js"></script>
<script type="text/javascript">
  var client = new JsonapiClient("http://localhost:16006/rest", {
    header: {
      authToken: "2ad1d6f7-e1d0-480d-86b2-dfad8af4a5b3"
    }
  });
</script>

Creating a new Client

var JsonapiClient = require("jsonapi-client");
var client = new JsonapiClient("http://localhost:16006/rest", {
  header: {
    authToken: "2ad1d6f7-e1d0-480d-86b2-dfad8af4a5b3"
  }
});

Creating a new Resource

var article = client.create("articles");
article.set("title", "foobar");
article.sync(function(err) {
  console.log("Resource created");
});

Finding Resources

client.find("articles", function(err, resources) {
  resources.map(function(resource) {
    console.log(resource.toJSON());
  });
});

Getting a specific Resource

client.get("articles", 5, { include: [ "author" ] }, function(err, article) {
  console.log(article.toJSONTree());
});

Fetching a Resource's related Resource

article.fetch("author", function(err) {
  console.log(article.author.toJSON());
});

Updating a Resource's primary relationships

article.relationships("comments").add(comment);
article.sync(function(err) {
  console.log("Resource's relation updated");
});

Deleting a Resource

article.delete(function(err) {
  console.log("Resource deleted");
});

A more complex example

}).then(function() {
  return client.create("articles")
    .set("title", "some fancy booklet")
    .set("content", "oh-la-la!")
    .relationships("tags").add(someTagResource)
    .sync();
}).then(function(newlyCreatedArticle) {