Initialize your node project, this will create a package.json file.
$ node init
Install hapi.js plugin for Restful APIs.
$ npm install hapi --save
Create a Node Hapi Server
server.js
Open text editor, copy following code. Here const (JavaScript ES6) is a identifier won’t be reassigned, if you want you can use var.
'use strict';
const Hapi = require('hapi');
// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 8000
});
// Add the route
server.route({
method: 'GET',
path:'/helloworld',
handler: function (request, reply) {
return reply('hello world');
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
Run Project
$ sudo npm start
Open your browser and launch the following URL, you will find "hello world" result.
http://localhost:8000/helloworld
Database Connection
MySQL Database
Install MySQL package for Node using node package manager(NPM).
$ npm install mysql --save
server.js
Modify the server.js and include MySQL connection code. Here you have to modify the MySQL database name, host, username and password.
'use strict';
const Hapi = require('hapi');
const MySQL = require('mysql');
// Create a server with a host and port
const server = new Hapi.Server();
const connection = MySQL.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database_name'
});
server.connection({
host: 'localhost',
port: 8000
});
connection.connect();
.....
.....
.....
Get Users Details
Here is the route for users data. Download poster extension for Chrome browser, this will help you to test these Restful APIs.
http://localhost:8000/users
server.route({
method: 'GET',
path: '/users',
handler: function (request, reply) {
connection.query('SELECT uid, username, email FROM users',
function (error, results, fields) {
if (error) throw error;
reply(results);
});
}
});
Working with Parameters
Parameter Validations
For valid inputs, install Joi package for Node.
$ npm install joi --save
Username validation minimum value 3 characters and maximum 30.
username: Joi.string().alphanum().min(3).max(30).required()
Password regular expression min 8 and max 30
password: Joi.string().regex(/^[a-zA-Z0-9]{8,30}$/)
Message validation supports both strings and numbers.
message: [Joi.string(), Joi.number()]
Birth year validation
birthyear: Joi.number().integer().min(1900).max(2013)
Email validation
email: Joi.string().email()
Get User Data
Here getting the user data based on uid value, Joi.number().integer() validating the user id input.
http://localhost:8000/user/1
const Joi = require('joi');
server.route({
method: 'GET',
path: '/user/{uid}',
handler: function (request, reply) {
const uid = request.params.uid;
connection.query('SELECT uid, username, email FROM users WHERE uid = "' + uid + '"',
function (error, results, fields) {
if (error) throw error;
reply(results);
});
},
config: {
validate: {
params: {
uid: Joi.number().integer()
}
}
}
});
POST
Get user message details, post parameters works with payload.
http://localhost:8000/messages
server.route({
method: 'POST',
path: '/messages',
handler: function (request, reply) {
const uid = request.payload.uid;
connection.query('SELECT * FROM messages WHERE uid_fk = "' + uid + '"',
function (error, results, fields) {
if (error) throw error;
reply(results);
});
},
config: {
validate: {
payload: {
uid: Joi.number().integer()
}
}
}
});
Delete
Delete user message data based on user and message ids.
http://localhost:8000/message/1/3
server.route({
method: 'DELETE',
path: '/message/{uid}/{mid}',
handler: function (request, reply) {
const uid = request.params.uid;
const mid = request.params.mid;
connection.query('DELETE FROM messages WHERE uid_fk = "' + uid + '"AND
mid = "' + mid + '"',
function (error, result, fields) {
if (error) throw error;
if (result.affectedRows) {
reply(true);
} else {
reply(false);
}
});
},
config: {
validate: {
params: {
uid: Joi.number().integer(),
mid: Joi.number().integer()
}
}
}
});
Encryption
We need to encrypt user password, bcrypt package will provide you the salt encryption code.
$ npm install bcrypt --save
POST User Signup
User signup with encrypted user password.
server.route({
method: 'POST',
path: '/signup',
handler: function (request, reply) {
const username = request.payload.username;
const email = request.payload.email;
const password = request.payload.password;
//Encryption
var salt = Bcrypt.genSaltSync();
var encryptedPassword = Bcrypt.hashSync(password, salt);
//Decrypt
var orgPassword = Bcrypt.compareSync(password, encryptedPassword);
connection.query('INSERT INTO users (username,email,passcode) VALUES
("' + username + '","' + email + '","' + encryptedPassword + '")',
function (error, results, fields) {
if (error) throw error;
reply(results);
});
},
config: {
validate: {
payload: {
username: Joi.string().alphanum().min(3).max(30).required(),
email: Joi.string().email(),
password: Joi.string().regex(/^[a-zA-Z0-9]{8,30}$/)
}
}
}
});
good
ReplyDelete