DEV Community 👩‍💻👨‍💻

Helder B. Berto
Helder B. Berto

Posted on

🔥 Quick Tip: How to create a Factory method pattern

On this simple trick, I'll show you how to create a Factory method pattern.

function HttpErrorFactory(statusCode, error = 'Uncaught Error!') {
  if (!statusCode) {
    throw new Error('Invalid status code.');
  }

  function make() {
    return {
      statusCode,
      error,
    };
  }

  function print() {
    const _response = make();
    return console.log(JSON.stringify(_response));
  }

  return { 
    make,
    print
  };
}

const badRequest = HttpErrorFactory(400, 'Bad Request!');
const badRequestObject = badRequest.make();

const internalServerError = HttpErrorFactory(500, 'Internal Server Error!');
const internalServerErrorObject = internalServerError.make();

console.log(badRequestObject);
/**
 * => {
        error: "Bad Request!",
        statusCode: 400
      }
 */

console.log(internalServerErrorObject);
/**
 * => {
        error: "Internal Server Error!",
        statusCode: 500
      }
 */

internalServerError.print();
// => "{\"statusCode\":500,\"error\":\"Internal Server Error!\"}"

badRequest.print();
// => "{\"statusCode\":400,\"error\":\"Bad Request!\"}"
Enter fullscreen mode Exit fullscreen mode

Did you like it? Comment, share! ✨

Oldest comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!