lengoo-api-response-formatter

1.2.1 • Public • Published

Lengoo API Response Formatter

A library to keep your responses formatted and consistent through your project.

Introduction

This library intends to create a consistent response format to be used through your project.

Features:

  • Most used HTTP Status codes;
  • Predefined error messages;
  • HTTP status guessing;
  • Mongo errors treatment;
  • Remove __v from mongo results;
  • Response formatter.

Output format

Success
{
    data: [...],
    error: {},
    validations: []
}
Error
{
    data: [],
    error: {
        code: "some-code",
        message: "Some message for humans"
    },
    validations: []
}
Validation error
{
    data: [],
    error: {
        code: "validation-error",
        message: "The request was not processed due to validation issues"
    },
    validations: [
        {
            code: "some-code",
            message: "Some message for humans",
            attribute: "attribute-that-caused-the-error",
            value: "given-value-for-attribute"
        },
        ...
    ]
}

Install

npm install --save lengoo-api-response-formatter

Usage

...

module.exports.get = (req, res) => {
    let response = new Response();

    Model.findOne({_id: req.swagger.params.id.value}, (err, doc) => {
        if (err) {
            response.mongoError = err;
        } else if (company === null) {
            response.error = Response.ERRORS.NOT_FOUND;
        } else  {
            response.data = doc;
        }

        res.status(response.status);
        res.json(response.get());
    });
};

...

Validations

You can add validations in two ways:

...

response.validation = [{
    code: "some-validation-code",
    message: Human message"',
    attribute: "attribute-that-caused-the-error",
    value: "given-value-for-attribute"
},
{
    code: "another-validation-code",
    message: Human message"',
    attribute: "attribute-that-caused-the-error",
    value: "given-value-for-attribute"
}];

...

Or:

...

response.addValidation = {
    code: "another-validation-code",
    message: "Human message",
    attribute: "attribute-that-caused-the-error",
    value: "given-value-for-attribute"
};

...

If you do not specify an error, the default error for validations will be added to the response.

API

.status

Default: 200

set

Define the HTTP response code.

Accepted types:
  • integer
Examples:
let response = new Response();
response.status = Response.CODES.BAD_REQUEST;
// Or
// response.status = 400;

get

Get the HTTP response code.

Example:
let response = new Response();
response.status = Response.CODES.BAD_REQUEST;
console.log(response.status);

.data

set

Set the data to be returned on data response property.

Note: The 200 status code will be added to the response.

Accepted types:
  • Array
  • Object
Example:
let response = new Response();
response.data = [{
    _id: 5ad60b78779c4e0ec54aa0d7,
    name: 'Lengoo'
}];

.error

set

Set the error to be returned on error response property.

Important: If the given value is one of the predefined error messages, the library will try to set the response status.

Accepted types:
  • Object
Examples:

Custom error:

let response = new Response();
response.error = [{
    code: 'some-custom-code',
    message: 'Something went wrong.'
}];

Predefined error:

let response = new Response();
response.status = Response.CODES.BAD_REQUEST;

.mongoError

set

Set the mongo error to be treated by the library.

The library will try to identify the error type, set the correct HTTP status and construct the appropriated response data;

Accepted types:
  • Object (Mongo Error)
Example:
let response = new Response();

Model.find({}, (err, doc) => {
    if (err) {
        response.mongoError = err;
    } else {
        response.data = doc;
    }

    res.status(response.status);
    res.json(response.get());
});

.validations

set

Set a collection of validation errors to be returned on validations response property.

Accepted types:
  • Array

Important: the items of the given array must to be objects.

Example:
let response = new Response();
response.validations = [
    {
       code: "some-validation-code",
       message: Human message"',
       attribute: "attribute-that-caused-the-error",
       value: "given-value-for-attribute"
   },
   {
       code: "another-validation-code",
       message: Human message"',
       attribute: "attribute-that-caused-the-error",
       value: "given-value-for-attribute"
    }
];

.addValidation()

Append a single validation error to the validations collection.

Accepted types:
  • Object
Example:
let response = new Response();
response.addValidation({
   code: "another-validation-code",
   message: Human message"',
   attribute: "attribute-that-caused-the-error",
   value: "given-value-for-attribute"
});

.get()

Retrieve the formatted response.

Example:
let response = new Response();
response.error = Response.ERRORS.BAD_REQUEST;
res.json(response.get());

Static

HTTP Codes

Values:
SUCCESS: 200,
CREATED: 201,
ACCEPTED: 202,
NO_CONTENT: 204,
BAD_REQUEST: 400,
MOVED_PERMANENTLY: 301,
FOUND: 302,
SEE_OTHER: 303,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
CONFLICT: 409,
UNPROCESSABLE_ENTITY: 422,
INTERNAL_SERVER_ERROR: 500,
NOT_IMPLEMENTED: 501,
SERVICE_UNAVAILABLE: 503
Example:
let response = new Response();
response.status = Response.CODES.NOT_FOUND;

Error messages

Values:
BAD_REQUEST: {
    code: 'bad-request',
    message: 'The given data could not been processed'
},
UNAUTHORIZED: {
    code: 'unauthorized',
    message: 'Authentication failed or was not provided'
},
FORBIDDEN: {
    code: 'forbidden',
    message: 'You don\'t have the required permissions to complete this operation'
},
NOT_FOUND: {
    code: 'not-found',
    message: 'The requested object was not found'
},
CONFLICT: {
    code: 'conflict',
    message: 'The request was not processed due to a conflict'
},
UNPROCESSABLE_ENTITY: {
    code: 'validation-error',
    message: 'The request was not processed due to validation issues'
},
INTERNAL_SERVER_ERROR: {
    code: 'internal-server-error',
    message: 'The server is unable to process the request at this time'
},
NOT_IMPLEMENTED: {
    code: 'not-implemented',
    message: 'The requested route was not implemented'
},
SERVICE_UNAVAILABLE: {
    code: 'service-unavailable',
    message: 'The server is currently unavailable'
}
Example:
let response = new Response();
response.error = Response.ERRORS.UNPROCESSED_ENTITY;

Tests

Coming soon

Package Sidebar

Install

npm i lengoo-api-response-formatter

Weekly Downloads

1

Version

1.2.1

License

MIT

Unpacked Size

17.8 kB

Total Files

4

Last publish

Collaborators

  • belzee92
  • mpedroc90
  • dejimenez
  • rodrigoterminus
  • daemyn
  • bretanac.93
  • lengoo_npm