http-response-helper
TypeScript icon, indicating that this package has built-in type declarations

2.1.0 • Public • Published

http-response-helper

dt l min types v

npm

Introduction

http-response-helper is a simple utility library that helps you create HTTP responses with correct status codes and messages.

Installation

npm install http-response-helper

Example Usage with Express.js

1. Creating a New Item

const { HttpResponseHelper } = require("http-response-helper");
const express = require("express");

const app = express();

app.use(express.json());

app.post("/create-item", (req, res) => {
 const data = req.body;

 // Logic to create the item

 // Send the HTTP response with status code 201 (Created)
 HttpResponseHelper.CREATED(res, data);
});

app.listen(3000, () => {});

Sample Response for Creating a New Item

{
 "code": 201,
 "data": {},
 "message": "Created"
}

2. For Getting an Item but Not Found

const { HttpResponseHelper } = require("http-response-helper");
const express = require("express");

const app = express();

app.use(express.json());

app.get("/not-found", (req, res) => {
 const { id } = req.query;

 // Logic to find the item (simulate item not found)

 // Send 404 response with custom message
 HttpResponseHelper.NOT_FOUND(res, { id }, "Item not found.");
});

app.listen(3000, () => {});

Sample Response for Getting an Item but Not Found

{
 "code": 404,
 "data": {},
 "message": "Item not found."
}

Available HTTP Response Methods

1xx: Informational - Request received, continuing process

  • CONTINUE
  • EARLY_HINTS
  • PROCESSING
  • SWITCHING_PROTOCOLS
  • UPLOAD_RESUMPTION_SUPPORTED

2xx: Success - The action was successfully received, understood, and accepted

  • ACCEPTED
  • ALREADY_REPORTED
  • CREATED
  • IM_USED
  • MULTI_STATUS
  • NO_CONTENT
  • NON_AUTHORITATIVE_INFORMATION
  • OK
  • PARTIAL_CONTENT
  • RESET_CONTENT

3xx: Redirection - Further action must be taken in order to complete the request

  • FOUND
  • MOVED_PERMANENTLY
  • MULTIPLE_CHOICES
  • NOT_MODIFIED
  • PERMANENT_REDIRECT
  • SEE_OTHER
  • TEMPORARY_REDIRECT

4xx: Client Error - The request contains bad syntax or cannot be fulfilled

  • BAD_REQUEST
  • CONFLICT
  • FORBIDDEN
  • NOT_FOUND
  • UNAUTHORIZED

5xx: Server Error - The server failed to fulfill an apparently valid request

  • BAD_GATEWAY
  • GATEWAY_TIMEOUT
  • INTERNAL_SERVER_ERROR
  • NOT_IMPLEMENTED
  • SERVICE_UNAVAILABLE

References

Package Sidebar

Install

npm i http-response-helper

Weekly Downloads

3

Version

2.1.0

License

MIT

Unpacked Size

15.5 kB

Total Files

9

Last publish

Collaborators

  • umairshabbir