What's the status code again ๐Ÿค”?

What's the status code again ๐Ÿค”?

ยท

3 min read

That's the question I get when working on a Node.js project. I also ask that alot.

I got tired of always googling this stuff, a decided the needed to be package to handle this.

I was inspired by Sails.js custom responses, I thought it would be nice to build a package for express.js to help out with setting the right status codes. So I built good-status

This is a very simple package that adds extra functions to the Node.js response object.

How to install

# NPM
npm i good-status

Initializing the middleware

Like every other package, you have to import it and add it as an express middleware.

var express = require("express");
var goodStatus = require("good-status");
var app = express ();

// add the magic middleware
app.use(goodStatus());

Using your new functions

Send response with valid status code by using the methods available

app.post("/", (req, res) => {
  res.created({
    status: "success",
    data: { name: "John Doe" },
  }); // { status: "success", data: {name: "John Doe"} }, 201
});

res.ceated() sends a status code of 201

app.get("/user", (req, res) => {
  res.notFound(); // 404
});

and res.notFound() sends a status code of 404.

By default if you pass in anything as a parameter, it gets sent in the response body as well.

In order to send your response body separately, you can initialize it like this

app.use(goodStatus({ send: false }));

And then send your response this way

res.unauthorized();
res.json({foo: "bar"});

Example

app.get("/admin", (req, res) => {
  const data = { msg: "require authentication" };
  res.unauthorized();
  res.json(data); // { msg: "require authentication" }, 401
});

First time ?

Oh! yes this is the first version, and very well my first package on NPM, and it really does the job.

I invite you to check this out and recommend other features or point out area that may potentially be a problem. And if you wish to contribute to it, then you are welcome in advance

GitHub link: github.com/micaiah-effiong/good-status