npm init
npm i -S hapi hapi-swagger inert vision joi
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'),
}
}
},
});
})();
node server
打开浏览器:http://localhost:3000/documentation