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

rest-api-response

v0.7.83

Published

express rest api response

Downloads

5

Readme

Rest API Response interface

A shorter way to send NodeJs rest-api response.

$ npm install apiresponse --save

if NODE_ENV is set to 'dev' it will show the message and error body ( for development ).

  • success - is response a success or not
  • status - Response status code.
  • data - response data
  • error - error object
  • error - errorId - contains Automatically Generated ErrorID
  • error - message - Message to the client about the error ( 404,401,500 and 403 will return static message unless in development mode)

usage: To make express async capable and help me along i used this

const {APIResponse} = require('rest-api-response');
module.exports = (handler) =>
    async (req, res, next) => {
        try {
            new APIResponse(res).success(
                await handler(req, next)
            )
        } catch (error) {
            next(error);
        }
    };

This allows me to simply return the response without any hustle. example of 404 handler

const
    {NotFoundError} = require('./rest-api-apiresponse');
    
router.use('/', asyncify(
    async (req) => {
        throw new NotFoundError("[" + req.method + "] - " + req.path);
    }
));

example of async handler with response + header

const
    asyncify = require('./helpers/asyncify.js'),
    {Response} = require('./rest-api-apiresponse');
    
router.use('/', asyncify(
    async (req) => {
        const email = await getUserEmail(req.query);
        
        const response = new Response({ userEmail: email });
        response.set('test-header', 'i am header');
        
        return response;
    }
));

Basic DOC

to return success:

const
    {APIResponse} = require('./rest-api-apiresponse');

router.get('/test', (req,res)=>{
    new APIResponse(res).success({ ok: true });
});

results in:

{
    "status":200,
    "data":{
        "ok":true
    },
    "error":null,
    "success":true
}

to return not found,unauthorized or forbidden:

const
    {APIResponse} = require('./rest-api-apiresponse');

router.get('/test', (req,res)=>{
    new APIResponse(res).notFound("Error Message");
    // new APIResponse(res).forbidden("Error Message");
    // new APIResponse(res).unauthorized("Error Message");
    // new APIResponse(res).serverError("Error Message");
});

results in

{
    status: 404,                                            // status according to the error
    data: null,                                             // Null when error is set
    error: {
        errorId: "47e0be0d-598b-4e48-b05c-f41cb704d02c",
        message: "Not Found",                               // "Not Found" unless in development mode
        body: {}                                            // empty unless in development mode
    },
    success: false
}

To return validation errors:

const
    {APIResponse} = require('./rest-api-apiresponse');

router.get('/test', (req,res)=>{
    new APIResponse(res).invalid("Custom Invalid Message");
});

results in

{
    status: 400,                                            //400
    data: null,                                             //data is null on validation error
    error: {
        errorId: "c5389ef8-3ac2-42b5-933d-b5df355b342c",    //Error ID
        message: "Custom Invalid Message",                  //Error Message passed from above
        body: {}
    }
},
success: false
}

To return a custom response:

const
    {APIResponse, Response} = require('./rest-api-apiresponse');

router.get('/test', (req,res)=>{
    const response = new Response({ok:true});
    response.set('Test-Header', 'The test worked');
    new APIResponse(res).success(response);
    return response;
});

OR

const
    {APIResponse, Response} = require('./rest-api-apiresponse');

router.get('/test', (req,res)=>{
    const response = new Response({ok:true}); 
    response.set('Test-Header', 'The test worked');
    
    new APIResponse(res).success(response); 
});

will set the Test-Header.


To add custom fields to response simply extend the Response object

const
    {APIResponse, Response} = require('./rest-api-apiresponse');

class CustomResponse extends Response{
    constructor(data){
        super(data);
        this.customField="custom"
    }
}
router.get('/test', (req,res)=>{
    const response = new CustomResponse({ok:true});
    new APIResponse(res).success(response);
});

will result in:

{
    "status":200,
    "data":{
        "ok":true
    },
    "customField":"custom",
    "error":null,
    "success":true
}