HTTP-Response-Helper

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

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

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

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

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

References