DEV Community

loading...

πŸ”₯ Quick Tip: How to create a Factory method pattern

helderburato profile image Helder Burato Berto ・1 min read

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! ✨

Discussion (0)

pic
Editor guide