如何在Hapi 17中抽象路线

时间:2018-02-08 13:57:45

标签: node.js routing hapijs

我正在研究如何将Hapi 16应用程序移至Hapi 17。

特别是我正在研究如何将当前的路由逻辑抽象为单独的目录和结构。

以下是有效的,但是是对的:

server.js

'use strict'

const Hapi = require('hapi')

const testRoutes = require('./routes/routes.test')
const jobRoutes = require('./routes/routes.jobs')

// Create a server with a host and port
const server = Hapi.server({
  host: 'localhost',
  port: 3000
})

const registerRoutes = () => {
  testRoutes.registerRoutes(server)
  jobRoutes.registerRoutes(server)
}

// Start the server
async function start () {

  try {
    await server.start()
  }
  catch (err) {
    console.log(err)
    process.exit(1)
  }

  console.log('Server running at:', server.info.uri)
}

registerRoutes()
start()

routes.test.js

const testCtrl = require('../src/TestController')

exports.registerRoutes = (server) => {
  server.route({
    method: 'GET',
    path: '/test/hello',
    handler: testCtrl.hello
  })

  server.route({
    method: 'GET',
    path: '/test/goodbye',
    handler: testCtrl.goodbye
  })
}

** TestController.js **

exports.hello = function (req, h) {
  return 'Hello test'
}

exports.goodbye = function (req, h) {
  return 'Goodbye test'
}

1 个答案:

答案 0 :(得分:1)

让我们这样试试。

在Hapi.js中你可以像插件一样对待所有东西(有一个关于它的约定,它不是一个意见)。将您的路由放到单独的文件夹和文件中,并将它们构建为插件。

例如

exports.plugin = {
    async register(server, options) {
        server.route([
            {
                method: 'GET',
                path: '/',
                options: {
                    description: 'main request handler',
                    handler: async (request, h) => {
                        return h.view('index', {'title': 'Home Page Title'});
                    }
                }
            },
            {
                method: 'GET',
                path: '/page/{id}',
                options: {
                    description: 'main request handler',
                    handler: async (request, h) => {

                        return h.view('detail_page', {'title': 'Detail Page', id: request.params.id});
                    }
                }
            },        
        ]);
    },
    version: require('../../package.json').version,
    name: 'route-main'
};

现在,您有一个插件可根据路径部分中的定义处理特定路由。 只需在您的服务器上注册此插件,就可以了。

以下是示例服务器代码。

const Hapi = require('hapi');

const startServer = async function() {

    const server = Hapi.Server();

    // just register your route
    await server.register({
        plugin: require('your-route-folder/and-file')
    });

    // let's say another route for only user and handles /users endpoint
    // now you can define your paths without repeating /users field on your route definition like /profile /detail/{id}
    // /users/profile, /users/detail/2
    // ref: https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options
    await server.register({
        plugin: require('your-route-folder/users'),
        options: {
            routes: {
                prefix: '/user'
            }
        }
    });


    await server.start();
    console.log(`Server started at ${server.info.uri}`);
};

startServer().catch((err) => {
    console.error(err);
    process.exit(1);
});