Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store routes in separate files when using Hapi?

All of the Hapi examples (and similar in Express) shows routes are defined in the starting file:

var Hapi = require('hapi');  var server = new Hapi.Server(); server.connection({ port: 8000 });  server.route({   method: 'GET',   path: '/',   handler: function (request, reply) {     reply('Hello, world!');   } });  server.route({   method: 'GET',   path: '/{name}',   handler: function (request, reply) {     reply('Hello, ' + encodeURIComponent(request.params.name) + '!');   } });  server.start(function () {   console.log('Server running at:', server.info.uri); }); 

However, it's not hard to image how large this file can grow when implementing production application with a ton of different routes. Therefore I would like to break down routes, group them and store in separate files, like UserRoutes.js, CartRoutes.js and then attach them in the main file (add to server object). How would you suggest to separate that and then add?

like image 954
Centurion Avatar asked Jan 04 '15 14:01

Centurion


People also ask

Is HAPI better than express?

One of the most significant differences between Hapi or HttpAPI and Express is the presence of middleware. Express needs middleware to parse objects, while Hapi does not need it. Apart from the middleware, many other features differ in Express and Hapi.

How do I serve a static file in Hapi?

Static file server The following example shows how to setup a basic file serve in hapi: const Path = require('path'); const Hapi = require('@hapi/hapi'); const Inert = require('@hapi/inert'); const init = async () => { const server = new Hapi. Server({ port: 3000, routes: { files: { relativeTo: Path.

What is Hapi swagger?

hapi-swagger This is a OpenAPI (aka Swagger) plug-in for Hapi When installed it will self document the API interface in a project.

Which function tells what to do when a GET request at the given route is called?

app. get() is a function that tells the server what to do when a get request at the given route is called. It has a callback function (req, res) that listen to the incoming request req object and respond accordingly using res response object.


2 Answers

You can create a separate file for user routes (config/routes/user.js):

module.exports = [     { method: 'GET', path: '/users', handler: function () {} },     { method: 'GET', path: '/users/{id}', handler: function () {} } ]; 

Similarly with cart. Then create an index file in config/routes (config/routes/index.js):

var cart = require('./cart'); var user = require('./user');  module.exports = [].concat(cart, user); 

You can then load this index file in the main file and call server.route():

var routes = require('./config/routes');  ...  server.route(routes); 

Alternatively, for config/routes/index.js, instead of adding the route files (e.g. cart, user) manually, you can load them dynamically:

const fs = require('fs');  let routes = [];  fs.readdirSync(__dirname)   .filter(file => file != 'index.js')   .forEach(file => {     routes = routes.concat(require(`./${file}`))   });  module.exports = routes; 
like image 102
Gergo Erdosi Avatar answered Sep 22 '22 14:09

Gergo Erdosi


You should try Glue plugin: https://github.com/hapijs/glue. It allows you to modularize your application. You can place your routes in separate subdirectories and then include them as Hapi.js plugins. You can also include other plugins (Inert, Vision, Good) with Glue as well as configure your application with a manifest object (or json file).

Quick exapmple:

server.js:

var Hapi = require('hapi'); var Glue = require('glue');  var manifest = {     connections: [{         port: 8080     }],     plugins: [         { inert: [{}] },         { vision: [{}] },         { './index': null },         {             './api': [{                 routes: {                     prefix: '/api/v1'                 }             }]         }     ] };   var options = {     relativeTo: __dirname + '/modules' };  Glue.compose(manifest, options, function (err, server) {     server.start(function(err) {         console.log('Server running at: %s://%s:%s', server.info.protocol, server.info.address, server.info.port);     }); }); 

./modules/index/index.js:

exports.register = function(server, options, next) {     server.route({         method: 'GET',         path: '/',         handler: require('./home')     }); });  exports.register.attributes = {     pkg: require('./package.json') }; 

./modules/index/package.json:

{     "name": "IndexRoute",     "version": "1.0.0" } 

./modules/index/home.js:

exports.register = function(req, reply) {     reply.view('home', { title: 'Awesome' }); }); 

Have a look at this wonderful article by Dave Stevens for more details and examples.

like image 41
coquin Avatar answered Sep 21 '22 14:09

coquin