rest-api-response-npm

0.1.4 • Public • Published

Installation

npm install rest-api-response-npm

Live DEMO:

Parameters

The successResponse, errorResponse, customResponse, checkValidation, validationResponse, catchError functions are JavaScript functions that are used to send HTTP responses from a server to a client. They take in the following parameters:

  • res - Parameter that represents the HTTP response object that will be sent back to the client.

  • err - Parameter that represents the error object that will be sent back to the client.

  • data - Parameter that represents the data that will be sent back to the client. This can be any JSON object or value.

  • message - Parameter that represents the message that will be sent back to the client along with the data.

  • statusCode - Parameter that represents the HTTP status code that will be sent back to the client.

Functions

  • successResponse: This function takes in four parameters, res (required), data (optional), message (optional), and statusCode (optional).

  • errorResponse: This function takes in four parameters, res (required), data (optional), message (optional), and statusCode (optional).

  • customResponse: This function takes in four parameters, res (required), data (optional), message (optional), and statusCode (optional).

  • validationResponse: This function takes in four parameters, res (required), data (required), message (optional), and statusCode (optional).

  • checkValidation: This function takes in four parameters, res (required) and req (required).

  • catchError: This function takes in four parameters, res (required) and err (required).


Usage

To use these functions in a Node.js application, simply import the module and call the desired function with the appropriate parameters. For example.

app.js

const express = require('express');
// const { ... } = require('rest-api-response-npm');
const { body } = require("express-validator");

const app = express();

// Use functions as per requiremet
// ...

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

successResponse() sample code:

const { successResponse } = require('rest-api-response-npm');

app.get('/', (req, res) => {
  const data = { 
    id: 12,
    user_name: 'Jaykumar Gohil'
 };
  successResponse(res, data, 'Success message', 200);
});

errorResponse() sample code:

const { errorResponse } = require('rest-api-response-npm');

app.get('/error', (req, res) => {
  let checkUser; // object
  let message; // object
  if(checkUser) {
    message = "User not exist!"
  }

  errorResponse(res, checkUser, message, 400);
  // or
  errorResponse(res, null, message, 400);
  // or
  errorResponse(res, null, message);
  // or
  errorResponse(res, null, 'Error message');
});

customResponse() sample code:

const { customResponse } = require('rest-api-response-npm');

app.get('/custom', (req, res) => {
  // Example 1
  const data = [
    {
        access_token: "asdasds.asdsadsasq2we23easa.asdasdasdas",
        name: 'namessss' 
    }
  ];
  customResponse(res, data, 'Login Successfully', 200);
  // or
  customResponse(res, data);
  
  // Example 2
  customResponse(res, null, 'Token Expiration', 401);
});

checkValidation() sample code:

const { checkValidation } = require('rest-api-response-npm');
const { body } = require("express-validator");

const validationRequest = [
  // validation for 
  // ...
  body("password")
    .notEmpty()
    .withMessage("Password is requierd")
    .isLength({ min: 6, max: 250 })
    .withMessage("Minimum 6 character password require")
    .trim(),
  // ...
]

app.post('/api/user', validationRequest, (req, res) => {
  // Validate the request parameters
  checkValidation(res, req);

  // If there are no validation errors, proceed with the request handling
  // ...
});

validationResponse() sample code:

const { validationResponse } = require('rest-api-response-npm');

app.post('/api/login', (req, res) => {
  // ...
  
  // Create validation formated data for invalid password API response
  data = {
      password: [
        "Invalid password",
      ]
  }
  validationResponse(res, data);
  // or
  validationResponse(res, data, "Validation failed!");
  // or
  validationResponse(res, data, "Validation failed!", 422);
});


catchError() sample code:

app.js

const { catchError } = require('rest-api-response-npm');

// ...

// default error messgae
app.use((error, req, res, next) => {
  // All types of errors in a project will be handled by this tool, and an error response will be provided in the proper format
  catchError(res, error);
});

// Use functions as per requiremet
// ...

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

demo:

app.get('/api/user', (req, res) => {
  try {
    // Handle the request and throw an error if needed
    // ...
  } catch (err) {
    // Use the next method to handle the error, and the catchError function will handle the response.
    next(err);
  }
});

Why Use Response Helper Functions?

  • REST APIs have become an integral part of modern web development, and this code offers a standardized and reliable approach to generate HTTP responses in a Node.js application. These functions, successResponse, errorResponse, and customResponse, checkValidation, validationResponse, catchError can be used as helpers to handle different types of responses in a consistent format.

  • By using these functions, you can prevent API format issues and save valuable development time. For frontend or mobile developers, these functions can be especially helpful since they provide a clear and predictable response structure that can be easily integrated into their application.

  • In addition to their practical benefits, using these functions is super easy to implement and use in your Node.js project. With just a few lines of code, you can experience the benefits of standardized and reliable HTTP responses.

  • By implementing these functions in your Node.js project, you can improve the overall user experience by providing clear and concise error messages and feedback. Give them a try and experience the benefits of standardized and reliable HTTP responses in your Node.js REST API development!


Conclusion

Above functions used for handling responses and errors in a server. successResponse is used to return a response with data, message, and status code, while errorResponse and customResponse handle errors and return responses accordingly. validationResponse reformats request parameters and returns an appropriate response, checkValidation validates request parameters and returns an appropriate response, and catchError is used to handle errors that occur during request processing and return a response with an error message.

Package Sidebar

Install

npm i rest-api-response-npm

Weekly Downloads

24

Version

0.1.4

License

MIT

Unpacked Size

11.8 kB

Total Files

3

Last publish

Collaborators

  • jksk21