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 Output for Creating a New Item

{
  "code": 201,
  "data": {
    "address": {
      "city": "Metropolis",
      "state": "NY",
      "street": "123 Main St",
      "zip": "12345"
    },
    "createdAt": "2024-11-16T10:00:00Z",
    "email": "johndoe@example.com",
    "firstName": "John",
    "id": 1,
    "isActive": true,
    "lastName": "Doe",
    "password": "securePassword123",
    "phone": "+1-555-555-5555",
    "profile": {
      "avatar": "https://randomuser.me/api/portraits/men/1.jpg",
      "bio": "Software developer and tech enthusiast",
      "socialLinks": {
        "github": "https://github.com/johndoe",
        "linkedin": "https://linkedin.com/in/johndoe",
        "twitter": "https://twitter.com/johndoe"
      }
    },
    "roles": [
      "admin",
      "user"
    ],
    "updatedAt": "2024-11-16T10:00:00Z",
    "username": "johndoe123"
  },
  "status": "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 message
 HttpResponseHelper.NOT_FOUND(res, {
  message: `Item not found for the ID: ${id}`,
 });
});

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

Sample Output for Getting an Item but Not Found

{
  "code": 404,
  "data": {
    "message": "Item not found for the ID: 1"
  },
  "status": "Not Found"
}

References