npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

lengoo-api-response-formatter

v1.2.1

Published

A lib to keep your responses formatted and consistent through your project

Downloads

12

Readme

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