Hi, in this post i’m going to show how to create a REST API using hapi.js and and couchbase. Hapi (pronounce as happy) is an open source web framework for node js, which is recommended for large and complex projects. Couchbase is a no-sql database that provides some special features like sync gateway which is a secure data synchronization method between web, mobile and IOT applications, N1QL sql query support, couchbase lite which and an offline-first database for mobile devices etc.
So, let’s get started!
First you need to install the couchbase server and then create a bucket in it.
If you are going to use N1QL queries in your API, make sure to create a primary index for the relevant bucket using following command
CREATE PRIMARY INDEX `your-bucket-name-primary-index` ON `your-bucket-name` USING GSI;
Then you have to create the app.js file within your project and add the following dependencies.
const hapi = require("hapi");
const couchbase = require("couchbase");
const joi = require("joi");
const UUID = require("uuid");
const N1qlQuery = Couchbase.N1qlQuery;
Now you need to install those dependencies using following command.
npm install couchbase hapi joi uuid --save
Then initiate the server and assign a host and a port and establish a connection with Couchbase by assigning bucket name and the host.
const server = new Hapi.Server({ port: 8080, host: 'localhost' });
const cluster = new Couchbase.Cluster("http://localhost");
const bucket = cluster.openBucket("medium_demo");
Finally you can start the Hapi server as following.
server.start(err => {
if (err) {
console.error(err);
throw err;
}
console.log(`Server started at ${ server.info.uri }`);
});
Now we can start working on the endpoints which interacts with our database. Our first endpoint is a POST method where we use Joi to validate the data. Since Couchbase is not giving any unique id for the records, we can add an unique id using uuid.
server.route({
method: "POST",
path: "/restaurant",
config: {
validate: {
payload: {
name: Joi.string().required(),
owner: Joi.string().required(),
address: Joi.string().required(),
telephone: Joi.number().required(),
type: Joi.string().required()
}
}
},
handler: (request, response) => {
bucket.insert(UUID.v4(), request.payload, (error, result) =>{
if(error) {
return response(error).code(500);
}
return response(request.payload);
});
}
});
Next we can create the GET method to return all the documents.
server.route({
method: "GET",
path: "/restaurant",
handler: (request, response) => {
var statement = "SELECT `" + bucket._name + "`.* FROM `" + bucket._name + "` WHERE type = 'restaurant'";
var query = N1qlQuery.fromString(statement);
bucket.query(query, (error, result) => {
if(error) {
return response(error).code(500);
}
return response(result);
});
}
});
Like this, it’s very easy to develop a simple API to perform CRUD operation using Hapi and the code is also simple and easy to understand. Happy Coding! :)
Code a Node.js Project with an Online IDE
☞ http://bit.ly/2tH1RyF
Learn Nodejs by building 12 projects
☞ http://bit.ly/2KrVFSm
ChatBots: Messenger ChatBot with API.AI and Node.JS
☞ http://bit.ly/2Jnm3w3
☞ JavaScript Programming Tutorial Full Course for Beginners
☞ Learn JavaScript - Become a Zero to Hero
☞ Javascript Project Tutorial: Budget App
☞ E-Commerce JavaScript Tutorial - Shopping Cart from Scratch