Skip to content

Latest commit

 

History

History
85 lines (70 loc) · 1.73 KB

1.2.0 使用Hapi-Swagger 插件配置接口文档.md

File metadata and controls

85 lines (70 loc) · 1.73 KB

使用 Hapi-Swagger 插件配置接口文档(v17)

install

npm init

npm i -S hapi hapi-swagger inert vision joi 

server.js

const Hapi = require('hapi');
const Inert = require('inert');
const Vision = require('vision');
const Joi = require('joi');
const HapiSwagger = require('hapi-swagger');
const Pack = require('./package');

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

    const swaggerOptions = {
        info: {
            title: 'Test API Documentation',
            version: Pack.version,
        },
    };

    await server.register([
        Inert,
        Vision,
        {
            plugin: HapiSwagger,
            options: swaggerOptions
        }
    ]);

    try {
        await server.start();
        console.log('Server running at:', server.info.uri);
    } catch (err) {
        console.log(err);
    }

    server.route({
        method: 'GET',
        path: '/todo/{id}/',
        config: {
            handler:
                (request, h) => {
                // return a string
                return 'ok'

            },
            description: 'Get todo',
            notes: 'Returns a todo item by the id passed in the path',
            tags: ['api'], // ADD THIS TAG
            validate: {
                params: {
                    id: Joi.number()
                        .required()
                        .description('the id for the todo item'),
                }
            }
        },
    });
})();


run

node server

打开浏览器:http://localhost:3000/documentation

参考