hapi js, Mongoose, MongoDB

A new way to work with Hapi, MongoDB, Mongoose, Angular. Hapi js is a basic framework for building a REST API in Node.js. Hapi was created by Walmart Labs.

 

Here we will learn how to perform basic CRUD in Hapi.js, and in the next blog, we will learn to implement token based user authentication … click here to visit the blog

Repo LLink: Click here to visit the repository

CONFIG JS

module.exports = {
    server: {
        host: '0.0.0.0',
        port: 8000
    },
    database: {
        host: '127.0.0.1',
        port: 27017,
        db: 'DatabaseName',
        username: '',
        password: ''
    }
};

SERVER JS

var Hapi = require('hapi'),
    Routes = require('./routes'),
    config = require('./config'),
    Db = require('./database');
var server = Hapi.createServer(config.server.host, config.server.port, {
    cors: true
});
server.route(Routes.endpoints);
server.start(function() {
    console.log('Server started ', server.info.uri);
});

DATABASE JS

var Mongoose = require('mongoose'),
    config = require('./config');
Mongoose.connect('mongodb://' + config.database.host + '/' + config.database.db);
var db = Mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', function callback() {
    console.log("Connection with database succeeded.");
});
exports.Mongoose = Mongoose;
exports.db = db;

ROUTES JS

var Controller = require('./controller'),
    Static = require('./static');
exports.endpoints = [
  { method: 'GET', path: '/{somethingss*}', config: Static.get },
  { method: 'POST', path: '/user', config:Controller.create},
  { method: 'GET', path: '/user', config: Controller.getAll}, 
  { method: 'GET', path: '/user/{userId}', config: Controller.getOne}, 
  { method: 'PUT', path: '/user/{userId}', config: Controller.update}, 
  { method: 'DELETE', path: '/user/{userId}', config: Controller.remove}];

STATIC JS

exports.get = {
    handler: {
        directory: {
            path: '../client/src',
            index: true
        }
    }
}

CONTROLLER JS

MODEL JS

 

API Available

Now we have learned to perform basic CRUD in Hapi.js, next look into how to implement token based user authentication system using JWT in hapi.js click here to visit the blog

  1. Hi , Facing an issue with the project, Please help me to rectify it. PFB stacktrace info.

    E:\Development\Workspace\WebStorm\HapiStack\server\node_modules\hapi\node_module
    s\hoek\lib\index.js:731
    throw new Error(msgs.join(‘ ‘) || ‘Unknown error’);
    ^

    Error: Unknown handler: directory
    at Object.exports.assert (E:\Development\Workspace\WebStorm\HapiStack\server
    \node_modules\hapi\node_modules\hoek\lib\index.js:731:11)
    at Object.exports.defaults (E:\Development\Workspace\WebStorm\HapiStack\serv
    er\node_modules\hapi\lib\handler.js:105:14)
    at new module.exports.internals.Route (E:\Development\Workspace\WebStorm\Hap
    iStack\server\node_modules\hapi\lib\route.js:48:35)
    at internals.Connection._addRoute (E:\Development\Workspace\WebStorm\HapiSta
    ck\server\node_modules\hapi\lib\connection.js:361:17)
    at internals.Connection._route (E:\Development\Workspace\WebStorm\HapiStack\
    server\node_modules\hapi\lib\connection.js:353:18)
    at internals.Plugin._apply (E:\Development\Workspace\WebStorm\HapiStack\serv
    er\node_modules\hapi\lib\plugin.js:503:14)
    at internals.Plugin.route (E:\Development\Workspace\WebStorm\HapiStack\serve
    r\node_modules\hapi\lib\plugin.js:476:10)
    at Object. (E:\Development\Workspace\WebStorm\HapiStack\server\se
    rver.js:17:8)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)
    at startup (node.js:117:18)
    at node.js:951:3

  2. Installed Dependencies
    For server Mongoose, Joi, Boom Hapi.
    For Client angular,angular-route,angular-resource. (Version 1.4.7 for all 3)

    Looking at the stack trace, it clearly says it is related to routes.

    Am i missed any settings, which rectifies this issue Please suggest. Eagerly waiting for your reply.

    • You need the INERT module to make the routes work.

      Instead of “server.route(Routes.endpoints);” line add the following code in your server.js file and it will work

      server.register(Inert, function(err){
      if(err){
      throw err;
      }
      server.route(Routes.endpoints);
      });

  3. This tutorial uses old version of hapi.
    the createServer methode not available in updated version .
    @cronjadmin’s link is very usefull.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.