HapiJS global path prefix

ぐ巨炮叔叔 提交于 2019-12-10 01:48:08

问题


I'm writing an API on HapiJS, and wondering how to get a global prefix. For example, all requests should be made to:

https://api.mysite.com/v0/...

So I'd like to configure v0 as a global prefix. The docs (here) don't seem to mention it -- is there a good way to do this in HapiJS?


回答1:


If you put your API routing logic inside a Hapi plugin, say ./api.js:

exports.register = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/hello',
        handler: function (request, reply) {
            reply('World');
        }
    });

    next();

};

exports.register.attributes = {
    name: 'api',
    version: '0.0.0'
};

You register the plugin with a server and pass an optional route prefix, which will be prepended to all your routes inside the plugin:

var Hapi = require('hapi');

var server = new Hapi.Server()
server.connection({
    port: 3000
});

server.register({
    register: require('./api.js')
}, {
    routes: {
        prefix: '/v0'
    }
},
function(err) {

    if (err) {
        throw err;
    }

    server.start(function() {
        console.log('Server running on', server.info.uri)
    })

});

You can verify this works by starting the server and visiting http://localhost:3000/v0/hello.




回答2:


I was able to get it working for all routes with

var server = new Hapi.Server()
...
server.realm.modifiers.route.prefix = '/v0'
server.route(...)



回答3:


Matt Harrisson's answer is the hapi way to do it using plugins.

Alternatively if you don't want to create a plugin just to add a prefix, you can by hand, add the prefix to all your routes.

For instance I went for something like this:

  var PREFIX = '/v0';
  var routes = [/* array with all your root */];

  var prefixize = function (route) {  route.path = PREFIX + route.path;return route; }
  server.route(routes.map(prefixize));

Good point is that with something like this your can perform express-like mounting. ex:

 var prefixize = function (prefix, route) {  route.path = prefix + route.path;return route; }

server.route(adminRoutes.map(prefixize.bind({}, "/admin"))); //currying.
server.route(apiRoutes.map(prefixize.bind({}, "/api")));



回答4:


you can always start your index.js like this

if (!global.PREFIX) {
  global.PREFIX = '/v0';
}

this way everywhere inside your code you'll have access to PREFIX

that's how you can access to PREFIX

console.log(PREFIX); or var name = PREFIX+ "_somename";




回答5:


Take a look at hapi-auto-route. This plugin automaticaly register your routes from a directory

// Directory structure
// 
// node_modules/
// routes/
//  home.js
// server.js
// package.json

// routes/home.js
'use strict';

module.exports = {
    method: 'GET',
    path: '/',
    handler: (request, h) => 'Hello';
}

// server.js
'use strict';

const Hapi = require('hapi');

const server = Hapi.Server({
  port: 3000,
  host: 'localhost'
});

const init = async () => {
    await server.register(require('hapi-auto-route'));
    await server.start();
    console.log(`Server is running at: ${server.info.uri}`);
};

process.on('unhandledRejection', (error) => {
  console.log(error);
  process.exit();
});

init()

and add prefix to it:




回答6:


I’m late to this party but this came up in search results.. FWIW, I'm using this, built off of AdrieanKhisbe’s answer. It allows for setting multiple global prefixes and using sub-route prefixes (similar to how Django urls are laid out). Here is a sample with multiple route.js files and api route versions (the route handlers moved out for clarity):

/departments/routes.js

const { getDepartments, getDepartmentById } = require('./handlers');

module.exports = [
  { method: 'GET', path: '', handler: getDepartments },
  { method: 'GET', path: '/{id}', handler: getDepartmentById }
];

/users/routes.js

const { getUsersV1, getUserByIdV1, getUsersV2, getUserByIdV2 } = require('./handlers');

const userRoutesV1 = [
  { method: 'GET', path: '', handler: getUsersV1 },
  { method: 'GET', path: '/{id}', handler: getUserByIdV1 }
];

const userRoutesV2 = [
  { method: 'GET', path: '', handler: getUsersV2 },
  { method: 'GET', path: '/{id}', handler: getUserByIdV2 }
];

module.exports = { userRoutesV1, userRoutesV2 };

index.js

const Hapi = require('@hapi/hapi');
const departmentRoutes = require('./departments/routes');
const { userRoutesV1, userRoutesV2 } = require('./users/routes');

const init = async () => {
  const server = Hapi.server({
    port: 3000,
    host: 'localhost',
  });

  const allRoutes = [];

  const v1 = '/api/v1/';
  const v2 = '/api/v2/';

  const prefixer = (routeArray, apiPrefix, subRoutePrefix) => {
    routeArray.map(route => {
      route.path = `${apiPrefix}${subRoutePrefix}${route.path}`;
      allRoutes.push(route);
    });
  };

  prefixer(departmentRoutes, v1, 'departments');
  prefixer(userRoutesV1, v1, 'users');
  prefixer(userRoutesV2, v2, 'users');

  server.route(allRoutes);

  await server.start();
  console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', err => {
  console.log(err);
  process.exit(1);
});

init();


来源:https://stackoverflow.com/questions/27871324/hapijs-global-path-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!