如何将HapiJs连接到Swagger?

时间:2017-11-15 17:05:03

标签: javascript node.js hapijs

我正在尝试将Hapijs连接到招摇项目。我目前正在使用这个包

Hapi Swagger

这是我的代码:

const Inert = require('inert');
const Vision = require('vision');
server.register([
    Inert,
    Vision,
    {
        'register': require('hapi-swagger'),
        'options': options
    }
], (err) => {
    server.start((err) => {
        if (err) {
            console.log(err);
        } else {
            console.log('Server running at:', server.info.uri);
        }
    });
});

我收到此错误消息

  if (plugin.register.register) {                             // Required plugin
                           ^

TypeError: Cannot read property 'register' of undefined

依赖

 "hapi": "^16.6.2",
 "hapi-swagger": "^8.0.0",

2 个答案:

答案 0 :(得分:0)

我实施了hapi swagger,希望这对你有用。

'use strict';

const HapiSwagger = require('hapi-swagger');
const Inert = require('inert');
const Vision = require('vision');
const Config = require('config');
const DatabaseSetting = Config.get('DatabaseSettings');

//Register Swagger
const Pack = require('../package');

exports.register = (server, options,next) => {  
    server.register([
        Inert,
        Vision,
        {
            'register': HapiSwagger,
            'options': {
                'info': {
                    'title': `API Documentation for  ${DatabaseSetting.env} environment`,
                    'version': Pack.version,
                    //'description':'Please use "accept :application/vnd.easyme.version.v1+json" for api versioning'
                },
                 'schemes': ['http'],
                'pathPrefixSize':2,
                'basePath': '/',
                documentationPath:'/doc',
                debug:true
            }
        }], (err) => {
        if (err) {
            server.log(['error'], `hapi-swagger load error: ${err}`)
        }else{
            server.log(['start'], 'hapi-swagger interface loaded')
        }
    });
    next();
};

exports.register.attributes = {
    name: 'swagger-plugin'
};

并且在server.js我有导入文件并像这样注册

// Register All Plugins
server.register(Plugins, err => {
  if (err) {
    server.error(`Error while loading plugins : ${err}`)
  } else {
    server.log('info', 'Plugins Loaded')
  }
})

答案 1 :(得分:0)

我为swagger插件注册创建了一个单独的文件。您可以添加类似的文件,只需要传递服务器上下文来注册插件。

如果你没有在你的项目中使用它们,你可以删除Winston和Raven(Sentry.io)。

package.json

的片段
/**
 * Embeds Hapi-Swagger plugin to the server
 */

/* jslint node: true */
/* jshint esversion: 6 */

'use strict';

const Inert = require('inert');
const Vision = require('vision');
const Winston = require('logger/WinstonPlugin');
const Raven = require('errors/RavenPlugin');
const environment = require('config').environment;
const port = require('config').port;

const swaggerOptions = {
    info: {
        title: 'API Documentation - [' + environment + ':' + port + ']'
    },
    tags: [{
        name: 'user',
        description: 'Related to User Object'
    }, {
        name: 'email',
        description: 'For verification of User Email'
    }, {
        name: 'session',
        description: 'Session Management'
    }, {
        name: 'account',
        description: 'User Account'
    }],
    jsonEditor: true,
    grouping: 'tags',
    securityDefinitions: {
        Bearer: {
            type: 'apiKey',
            name: 'Authorization',
            in: 'header',
            "scopes": {
                "write:pets": "modify pets in your account",
                "read:pets": "read your pets"
            }
        }
    }
};

/**
 * Registers Swagger Plugin in Hapi Server object
 * @param {*} server - Hapi.Server
 */
function RegisterSwaggerPlugin(server) {

    if (!server) return;

    server.register([Inert, Vision,
        {
            register: require('hapi-swagger'),
            options: swaggerOptions
        }
    ], function (err) {
        if (err) {
            Winston.error(['error'], 'hapi-swagger load error: ' + err);
            Raven(err);

        } else {
            Winston.debug('hapi-swagger interface loaded');
        }
    });
}

module.exports = RegisterSwaggerPlugin;

<强> HAPI-swagger.js

// Add Swagger Plugin here
require('plugin-registration/hapi-swagger')(server);

您可以像这样注册server.js文件中的插件。

<强> server.js

public function rules()
    {
        return [
            [['id', 'editedby', 'cat_id', 'prod_id', 'parent', 'order', 'status'], 'integer'],
            [['name', 'content', 'excerpt', 'date', 'url', 'posttype'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Posts::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params,'');

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'date' => $this->date,
            'editedby' => $this->editedby,
            'cat_id' => $this->cat_id,
            'prod_id' => $this->prod_id,
            'parent' => $this->parent,
            'order' => $this->order,
            'status' => $this->status,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'content', $this->content])
            ->andFilterWhere(['like', 'excerpt', $this->excerpt])
            ->andFilterWhere(['like', 'url', $this->url])
            ->andFilterWhere(['like', 'posttype', $this->posttype]);

        return $dataProvider;
    }

因此,只要您想阻止插件注册,就可以通过注释单行来实现。