@appcominteractive/appcom-hapi-documentation
v1.0.6
Published
This is a node module to generify and simplify documentation of hapi.js api gateways
Downloads
33
Readme
appcom-hapi-documentation
This module enables you to easily set up a working documentation environment for your Hapi.js service.
Installation
npm install --save(-dev) @appcominteractive/appcom-hapi-documentation
Configuration
Afterwards you can register this module as a Hapi.js plugin. This module comes with Hapi-Swagger pre-installed. You just have to make sure, that you installed any Hapi.js v16, and the Hapi.js Inert plugin inside your main project:
// index.js
const Hapi = require('hapi'); // You've to install the hapi dependency in your main project
const appcomHapiDoc = require('@appcominteractive/appcom-hapi-documentation');
[...]
// Set up your hapi server as you like. Example:
const server = new Hapi.Server({
connections: {
routes: {
timeout: {
server: 600000,
socket: 600001
}
}
}
});
server.connection({
port: config.http.port
});
[...]
// Set up inert plugin like this. Maybe you want to implement some error handling
server.register(Inert, (err) => {});
[...]
// Now set up this Hapi.js plugin
server.register({
register: appcomHapiDoc,
options: {
hapiSwaggerOptions: { // This will be passed directly to Hapi-Swagger: https://github.com/glennjones/hapi-swagger/blob/v7.x/optionsreference.md
info: {
title: 'Your Projects-Name API documentation',
version: '0.0.1'
},
sortEndpoints: 'ordered',
grouping: 'tags',
basePath: '/api/v1/',
host: 'http://example.com',
schemes: ['http'],
definitionPrefix: 'useLabel'
},
enableDocumentation: process.env.NODE_ENV === 'development', // Enables or disables the documentation route. Default: true
documentationFolder: 'documentation', // Specify the folder relative to your project root folder where your documentation is placed. Default: 'documentation'
extendMiddlewares: (middlewares, hapiConfig) => {
if (middlewares.some(middleware => middleware.assign === 'multipart')) {
hapiConfig.payload = {
maxBytes: (config.uploads || { maxSizeInMB: 5 }).maxSizeInMB * (1024 * 1024),
output: 'stream',
parse: true,
timeout: 600000
};
}
} // If needed, you may specify a helper method here, which can extend given middlewares when setting up routes. For example you can set the max file size here for file uploads
}
}, (err) => {
if (err) {
// Handle any errors which may occur
}
});
Default Hapi-Swagger configuration, if not specified:
{
info: {
title: 'TITLE HAS NOT BEEN SET YET',
version: '0.0.1'
},
sortEndpoints: 'ordered',
grouping: 'tags',
basePath: '/api/v1/',
definitionPrefix: 'useLabel'
}
Set up new routes inside your main project
With this node module you can simply add new routes to your Hapi.js server:
// routes.js
const controller = require('./sessionController');
server.get('/api/v1/session', controller.get); // (req, res) will be passed to your method
server.post('/api/v1/session', controller.post); // (req, res) will be passed to your method
server.put('/api/v1/session', controller.put); // (req, res) will be passed to your method
server.delete('/api/v1/session', controller.delete); // (req, res) will be passed to your method
Set up documentation inside your main project
Now create some new files inside your specified documentation directory:
// controller.js
const Joi = require('joi');
const errorBuilder = require('@appcominteractive/appcom-hapi-documentation').errorBuilder; // This module exposes some helper methods. See 'errorBuilder.js', 'responseBuilder.js' and 'globals.js' for more information
const globals = require('@appcominteractive/appcom-hapi-documentation').globals;
module.exports = {
'/api/v1/session': { // This key has to map to any of your api endpoints
post: { // This is the corresponding method
description: 'Create JWT',
notes: 'Creates a new user token (JWT) when given credentials are valid',
plugins: {
'hapi-swagger': {
payloadType: 'form',
responses: {
200: {
description: 'Success',
schema: Joi.object({
token: Joi
.string()
.required()
.description('Token which must be used for further actions')
.example('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1dWlkIjoiZTRjOTZhOTgtNGNlNS00ZjA0LWI3NGItNzcwYzQyN2E3NzM4IiwiaWF0IjoxNTE5MTE0Mzg5LCJleHAiOjE1MTk3MTkxODl9.9Z6IPGj5su7kNoFHagGdRAfN19yvTtnyySi59bqqSrU')
}).label('JwtResponse')
},
401: {
description: 'Unauthorized - Will be returned when the given credentials are invalid',
schema: errorBuilder({
statusCode: 401,
error: 'Unauthorized',
message: 'The user could not be authenticated',
code: 20004
}).label('InvalidCredentialsError')
},
400: {
description: 'Bad request - Will be returned if a parameter is missing',
schema: errorBuilder({
statusCode: 400,
error: 'Bad request',
message: 'Some parameters are missing',
code: 20000,
detail: Joi.array().items(
Joi.string().example('Email is missing'),
Joi.string().example('Password is missing')
).label('MissingParametersErrorDetail').required()
}).label('MissingParametersError')
},
404: {
description: 'Not found - Will be returned if there is no user registered with given e-mail-address',
schema: errorBuilder({
statusCode: 404,
error: 'Not found',
message: 'There is no user matching the given criteria',
code: 20003,
detail: Joi.object({
email: Joi.string().example('[email protected]').required()
}).label('UserNotFoundDetail').required()
}).label('UserNotFoundError')
}
}
}
},
validate: {
payload: Joi.object({
email: Joi.string().email().description('Users e-mail address').default('[email protected]'),
password: Joi.string().description('Password').default('Passwort')
})
},
tags: ['session']
}
}
};
License
Copyright 2018 appcom interactive GmbH
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.