quinta-feira, 26 de maio de 2016

Building APIs with HarvesterJS

HarvesterJS helps creating robust APIs on the top of mongoDB and node.js. It is a fork of fortuneJS and is JSONAPI compliant, and runs under Express. It gives the developer the ability to create contracts and validations with Joi.

In this post you'll see how to setup a very basic API with schema validations and some features of HarvesterJS.

Once the resources are properly set up, HarvesterJS provides the GET/POST/PUT/DELETE operations persisting the data on MongoDB.


Initial project setup

  • npm init
  • npm install harvesterjs --save
  • npm install joi --save


Seeting up the API with configs


app.js

var harvester = require('harvesterjs'),
    options = {
        adapter: 'mongodb',
        connectionString: 'mongodb://127.0.0.1:27017/mydb',
        inflect: true
    };
var harvesterApp = harvester(options);

require('./models/customer')(harvesterApp);
require('./models/contact')(harvesterApp);

function onListen() {
    console.log('listening on port 4567');
}

harvesterApp.listen(4567, onListen);



Setting up a resource


You can setup the resource fields and use JOI to describe and include validations on the field. In the examples below, we have a resource called customer with two fields: status and name

  • Status is a string which only accepts two values: Active or Inactive
  • Name is a string which is required.

Basic resource customer.js

var Types = require('joi');

harvesterApp.resource('customer', {
    status: Types.string().valid('Active', 'Inactive'),
    name: Types.string().required()
});


Linking resources



Regular link

In the example below, we have a resource called customer which has a link to a resource called contact. This link is an array of contacts, but you can have a single resource link.

var Types = require('joi');

harvesterApp.resource('customer', {
    status: Types.string().valid('Active', 'Inactive'),
    name: Types.string().required(),
    links: {
       contacts: ['contact']
    }
});


External link

In the example below, we have a resource called customer which has an external link to a resource called contact.

var Types = require('joi'),
   contactURI = 'http://localhost:2426/contacts';

harvesterApp.resource('customer', {
   status: Types.string().valid('Active', 'Inactive'),
   name: Types.string().required(),
   links: {
      contact: { ref: 'contact', baseUri: contactURI }
   }
});


Manipulating resources manually


HarvesterJS gives you the ability to manipulate documents manually. Once you have the harvesterApp object in place, you can use harvesterApp.adapter's methods to interact with mongoDB: find, findMany, create, update, delete.

These are the very basic features of HarvesterJS, for more information check its github.

Nenhum comentário:

Postar um comentário