tom-sapletta-com
12/14/2018 - 8:09 PM

Hapi-Swagger sample - Run and open "http://localhost:3000/documentation" in order to be shown the documents of your APIs.

Hapi-Swagger sample - Run and open "http://localhost:3000/documentation" in order to be shown the documents of your APIs.

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.json');

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

const options = {
  info: {
    'title': 'API Documentのタイトル',
    'description': 'APIの説明',
    'version': Pack.version,
  }
};

server.register([
  Inert,
  Vision,
  {
    'register': HapiSwagger,
    'options': options
  }
], (err) => {
  server.start((err) => {
    if (err) {
      console.log(err);
    } else {
      console.log('Server running at:', server.info.uri);
    }
  });
});


const handlers = {};
handlers.getToDo = function (request, reply) {
  const id = request.params.id;
  reply('todo ' + id);
};
handlers.getTest = function (request, reply) {
  reply('test is ok');
};

server.route({
  method: 'GET',
  path: '/todo/{id}',
  config: {
    handler: handlers.getToDo,
    description: 'Get Todo',
    notes: 'Returns a todo item by the id passed in the path',
    tags: ['api', 'v1'],
    validate: {
      params: {
        id: Joi.number()
          .required()
          .description('the id for the todo item'),
      }
    }
  },
});

server.route({
  method: 'GET',
  path: '/test',
  config: {
    handler: handlers.getTest,
    description: 'Get Test',
    notes: 'Returns a test message',
    tags: ['api', 'v1'],
  },
});