0.1.3 • Published 1 year ago

responseify v0.1.3

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Installation

npm install responseify

OR

yarn add responseify

Usage

// This example is created using express

const express = require('express');

const { HTTPResponseBuilder } = require("responseify"); // Require the HTTPResponseBuilder function from the responseify library

const posts = [
  {
    id: 1,
    content: "This is post 1",
    author: "poster1"
  },
  {
    id: 2,
    content: "This is post 2",
    author: "poster2"
  }
]

const app = express(); // Create an express app

app.get("/posts", async (req, res) => {

  const response = HTTPResponseBuilder({ // Use the HTTPResponseBuilder function to generate a standardized HTTP response object
    statusCode: 200, // Set the HTTP status code to 200 (OK)
    cause: 'Everything is working.', // Provide a brief description of the cause of the response
    metadata: posts, // Include the posts as metadata in the response
  })

  res.status(response.statusCode).json(response);
})

app.listen(3000);

RESPONSE

{
  "statusCode": 200,
  "message": "OK",
  "cause": "Everything is working.",
  "metadata": [
    {
      "id": 1,
      "content": "This is post 1",
      "author": "poster1"
    },
    {
      "id": 2,
      "content": "This is post 2",
      "author": "poster2"
    }
  ]
}

Documentation

You can use the send function to quickly and easily send a response to the user. To use it, simply call the .send() on the response object.

const response = HTTPResponseBuilder({
  "statusCode": 200,
  "metadata": {
    "post": {
      "author": "poster1"
    }
  }
});

// Node HTTP server
response.send(res);

// Express server
response.expressSend(res);

Use the .createRequestId() to generate a unique request id for your response.

const response = HTTPResponseBuilder({
  "statusCode": 200,
  "metadata": {
    "post": {
      "author": "poster1"
    }
  }
});

response.createRequestId();

If you only need to use certain ranges of status codes (e.g., 2xx success codes or 4xx client error codes), you can use tree shaking to access specific ranges of status codes like this:

const { _2XX } = require("responseify");

const response = new _2XX({
  statusCode: 200,
  metadata: {
    username: "carl212"
  }
})

Responseify supports all HTTP status codes listed on the HTTP status codes Wikipedia page.