@damien-laurent/http-responses

1.1.2 • Public • Published

HTTP RESPONSES

A simple library standardizing HTTP responses for an Express app.

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install express-requests-logger

Usage

// Works with objects
res.ok({ key: "value" });
// => 200 - { key: "value" }

// Works with strings
res.forbidden("You should not be here");
// => 403 - { message: "You should not be here" }

// Works with errors
res.internalServerError(new Error("This is an error message"))
// => 500 - { message: "This is an error message" }

Examples

All examples here.

Use all available responses

const httpResponses = require("@damien-laurent/http-responses");
const express = require("express");
const router = express.Router();

(async () => {
	try {
		// Declare express app
		const application = express();

		// Since express v4.16.0, express.json() replaces bodyparser.json()
		application.use(express.json());

		// Register all HTTP responses
		application.use(httpResponses.all());

		// Add a route
		router.get("/", (req, res) => res.ok({ key: "Great, it works with strings" }));
		router.post("/", (req, res) => res.forbidden("The access to this section is restricted."));

		// Routes: initialize router
		application.use("/", router);

		// Run application
		await application.listen(3000);
	}
	catch (error) {
		console.error(error.message);
	}
})();

Select some of available responses

const httpResponses = require("@damien-laurent/http-responses");
const express = require("express");
const router = express.Router();

(async () => {
	try {
		// Declare express app
		const application = express();

		// Since express v4.16.0, express.json() replaces bodyparser.json()
		application.use(express.json());

		// Register all HTTP responses
		application.use(httpResponses.select(["success.ok"]));

		// Add a route
		router.get("/", (req, res) => res.ok({ key: "Great, it works with strings" }));

		// Routes: initialize router
		application.use("/", router);

		// Run application
		await application.listen(3000);
	}
	catch (error) {
		console.error(error.message);
	}
})();

Create a custom response

const httpResponses = require("@damien-laurent/http-responses");
const express = require("express");
const router = express.Router();

(async () => {
	try {
		// Declare express app
		const application = express();

		// Since express v4.16.0, express.json() replaces bodyparser.json()
		application.use(express.json());

		// Create a custom HTTP response
		const customHttpResponse = httpResponses.custom("serverError", 500, console.log);

		// Register it to application
		application.use(customHttpResponse);

		// Add a route
		router.get("/", (req, res) => {
			try {
				throw new Error("Aie aie");
			}
			catch (error) {
				return res.serverError(error);
			}
		});

		// Routes: initialize router
		application.use("/", router);

		// Run application
		await application.listen(3000);
	}
	catch (error) {
		console.error(error.message);
	}
})();

Available responses

Basically, any response defined here is available.

2xx success

// 200 | OK
res.ok(response payload);

// 201 | Created
res.created(response payload);

// 202 | Accepted
res.accepted(response payload);

// 203 | Non-Authoritative Information (since HTTP/1.1)
res.nonAuthoritativeInformation(response payload);

// 204 | No Content
res.noContent(response payload);

// 205 | Reset Content
res.resetContent(response payload);

// 206 | Partial Content (RFC 7233)
res.partialContent(response payload);

// 207 | Multi-Status (WebDAV; RFC 4918)
res.multiStatus(response payload);

// 208 | Already Reported (WebDAV; RFC 5842)
res.alreadyReported(response payload);

// 226 | IM Used (RFC 3229)
res.imUsed(response payload);

3xx redirection

// 300 | Multiple Choices
res.multipleChoices(response payload);

// 301 | Moved Permanently
res.movedPermanently(response payload);

// 302 | Found (Previously "Moved temporarily")
res.found(response payload);

// 303 | See Other (since HTTP/1.1)
res.seeOther(response payload);

// 304 | Not Modified (RFC 7232)
res.notModified(response payload);

// 305 | Use Proxy (since HTTP/1.1)
res.useProxy(response payload);

// 306 | Switch Proxy
res.switchProxy(response payload);

// 307 | Temporary Redirect (since HTTP/1.1)
res.temporaryRedirect(response payload);

// 308 | Permanent Redirect (RFC 7538)
res.permanentRedirect(response payload);

4xx client errors

// 400 | Bad Request
res.badRequest(response payload);

// 401 | Unauthorized (RFC 7235)
res.unauthorized(response payload);

// 402 | Payment Required
res.paymentRequired(response payload);

// 403 | Forbidden
res.forbidden(response payload);

// 404 | Not Found
res.notFound(response payload);

// 405 | Method Not Allowed
res.methodNotAllowed(response payload);

// 406 | Not Acceptable
res.notAcceptable(response payload);

// 407 | Proxy Authentication Required (RFC 7235)
res.proxyAuthenticationRequired(response payload);

// 408 | Request Timeout
res.requestTimeout(response payload);

// 409 | Conflict
res.conflict(response payload);

// 410 | Gone
res.gone(response payload);

// 411 | Length Required
res.lengthRequired(response payload);

// 412 | Precondition Failed (RFC 7232)
res.preconditionFailed(response payload);

// 413 | Payload Too Large (RFC 7231)
res.payloadTooLarge(response payload);

// 414 | URI Too Long (RFC 7231)
res.uriTooLong(response payload);

// 415 | Unsupported Media Type (RFC 7231)
res.unsupportedMediaType(response payload);

// 416 | Range Not Satisfiable (RFC 7233)
res.rangeNotSatisfiable(response payload);

// 417 | Expectation Failed
res.expectationFailed(response payload);

// 418 | I'm a teapot (RFC 2324, RFC 7168)
res.imATeapot(response payload);

// 421 | Misdirected Request (RFC 7540)
res.misdirectedRequest(response payload);

// 422 | Unprocessable Entity (WebDAV; RFC 4918)
res.unprocessableEntity(response payload);

// 423 | Locked (WebDAV; RFC 4918)
res.locked(response payload);

// 424 | Failed Dependency (WebDAV; RFC 4918)
res.failedDependency(response payload);

// 425 | Too Early (RFC 8470)
res.tooEarly(response payload);

// 426 | Upgrade Required
res.upgradeRequired(response payload);

// 428 | Precondition Required (RFC 6585)
res.preconditionRequired(response payload);

// 429 | Too Many Requests (RFC 6585)
res.tooManyRequests(response payload);

// 431 | Request Header Fields Too Large (RFC 6585)
res.requestHeaderFieldsTooLarge(response payload);

// 451 | Unavailable For Legal Reasons (RFC 7725)
res.unavailableForLegalReasons(response payload);

5xx server errors

// 500 | Internal Server Error
res.internalServerError(response payload);

// 501 | Not Implemented
res.notImplemented(response payload);

// 502 | Bad Gateway
res.badGateway(response payload);

// 503 | Service Unavailable
res.serviceUnavailable(response payload);

// 504 | Gateway Timeout
res.gatewayTimeout(response payload);

// 505 | HTTP Version Not Supported
res.httpVersionNotSupported(response payload);

// 506 | Variant Also Negotiates (RFC 2295)
res.variantAlsoNegotiates(response payload);

// 507 | Insufficient Storage (WebDAV; RFC 4918)
res.insufficientStorage(response payload);

// 508 | Loop Detected (WebDAV; RFC 5842)
res.loopDetected(response payload);

// 510 | Not Extended (RFC 2774)
res.notExtended(response payload);

// 511 | Network Authentication Required (RFC 6585)
res.networkAuthenticationRequired(response payload);

Licence

MIT

Package Sidebar

Install

npm i @damien-laurent/http-responses

Weekly Downloads

6

Version

1.1.2

License

MIT

Unpacked Size

36.3 kB

Total Files

75

Last publish

Collaborators

  • dlaurentn