Format responses from hapi into JSend format.
Lead Maintainer: Robert Hernandez
JSend "lays down some rules for how JSON responses from web servers should be formatted." The intent of this hapi plugin is to format all messages from a hapi server into this format.
The following are quick examples of the JSend standard. Please visit their website for more information.
{
"status": "success",
"data": {
"post": { "id": 1, "title": "A blog post", "body": "Some useful content" }
}
}
{
"status": "fail",
"data": { "title": "A title is required" }
}
{
"status": "error",
"message": "Unable to communicate with database"
}
{
"status": "error",
"message": "Unable to communicate with database",
"code": 1,
"data": "Unable to communicate with database"
}
npm install hapi-jsend
const server = new Hapi.Server({
port: 3000,
host: 'localhost'
});
const init = async () => {
await server.register(require('hapi-jsend'));
await server.start();
console.info(`Server running at: ${server.info.uri}`);
};
init();
I decided to add a statusCode property to the payload as well. I personally always having to check to objects: the httpResponse and the payload to determine why a response is the way it is.
{
"status": "fail",
"data": {
"title": "A title is required"
}
}
{
"status": "fail",
"data": {
"title": "A title is required"
},
"statusCode": 400
}
I have taken the liberty to extend JSend a bit when it comes to the fail status. I believe that it should be more like error and allow for sub codes and messages. Think of a response like 404 in which content is really NOT_FOUND or content is known to be deleted. If we make fail more like error we can indicate this distinction while providing a useful message to the user.
{
"status": "fail",
"data": {
"title": "A title is required"
}
}
{
"status": "fail",
"message": "Bad Request",
"code": 1,
"data": {
"title": "A title is required"
},
"statusCode": 400
}
Both of the extensions described above are "opt-in" since they are non-standard.
{
"attachHttpStatusCode": true,
"extendFailResponse": true
}
await server.register({
plugin: require('hapi-jsend'),
options: {
attachHttpStatusCode: true,
extendFailResponse: true
}
});
An individual route can opt-out from JSend formatting.
server.route({
method: 'GET',
path: '/',
options: {
plugins: {
hapiJSend: {
optOut: true
}
},
handler: function(request, h) {
return "OK";
}
}
});