在 上一个实验 中,演示 HApi 如何使用扩展。本次实验我们将会演示如何自定义 HApi 扩展。
示例代码
在项目中新建一个名为: plugins 的目录,再在目录中新建一个名为: api-response-encode.js 的文件,在文件中填入以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const apiResponseEncode = { name: 'api-response-encode', version: '1.0.0', register: async function (server, options) {
server.ext({ type: 'onPostHandler', method: async (request, h) => { console.log('[onPostHandler]...data: %s', request.response.source) const res = { success: true, error_code: '', error_msg: '', data: request.response.source } return h.response(res) } }) } }
exports.plugin = apiResponseEncode
|
再在 plugins 目录中新建一个名为: helloPlugin.js 的文件,填入以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| 'use strict';
const myPlugin = { name: 'myPlugin', version: '1.0.0', register: async function (server, options) {
server.route({ method: 'GET', path: '/test', handler: function (request, h) {
return 'hello, Plugin'; }, config: { description: 'api: test', notes: 'Returns a string. "hello, Plugin" ', tags: ['api'] } });
} };
exports.plugin = myPlugin;
|
示例程序
新建一个名为: CustomPlugin.js 的文件。在文件中填入以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const Hapi = require('hapi');
const server = new Hapi.Server({ host: 'localhost', port: 8000 });
const start = async function() {
try {
await server.register(require('./plugins/api-response-encode'));
await server.register(require('./plugins/helloPlugin'));
await server.start();
console.log('Server running at:', server.info.uri);
} catch(err) { console.log(err); process.exit(1); } }
start();
|