Git Product home page Git Product logo

expressjs-utils's Introduction

expressjs-utils

This module contains a set of utilities that make our life easier while writing express apps. The minimum supported node version for this lib is v8.6.0.

Installation

$ yarn add expressjs-utils
$ npm install expressjs-utils

Usage

const utils = require("expressjs-utils");

start

start(app, port, env)

starts the express server unless you're in the test env

// starts your app on port 8082 with environment set to 'test'
utils.start(app, 8082, "test");

static

static(app, path)

mounts the static, /public folder

// assuminc your public folder is located at '/../../public'
utils.static(app);

// if it is located somewhere else, just pass the path, relative to the current file.
utils.static(app, "/../public");

getRouter

getRouter(app, prefix)

returns a router that prefixes all routes at /prefix & /prefix/vX or /vX, where X is a specific version of your api. Use it for API versioning & when you need a common prefix. If no API version is passed, that is vX is not present in the url, it will be set to 0 by default. You can access the API Version using req.apiVersion.

  let express = require('express');

  // You can also pass express to getRouter function
  let router = utils.getRouter(app, 'api', express);
  //OR use the default express from the library to create the router
  let router = utils.getRouter(app, 'api');

  router.get('/cars', (req, res, next) => {
    return res.json({...});
  });

  // Possible endpoint formats
  /api/v1/cars //req.apiVersion will be 1 here
  /api/cars //req.apiVersion will be 0 here

  let router = utils.getRouter(app, '');
  router.get('/people', (req, res, next) => {
    return res.json({...});
  });

  // Possible endpoint formats
  /v1/people //req.apiVersion will be 1 here
  /people
  //req.apiVersion will be 0 here

errorHandler

errorHandler(app, logger) provides a generic error handler that can be used at the "end" of your app logger is optional. If you want to use a logger that will give you a bit more details, you should just get our open-source logger and pass it to the error handler and we will use it, instead of console.error, to log the error.

// Add this after all your routes
utils.errorHandler(app);

// Then in any route you can simply call next(err) whenever an error occurs
router.post("/cars", async (req, res, next) => {
  try {
    let result = await getCars();
  } catch (err) {
    next(err);
  }
});

httpError

httpError(code=500, message='Internal Server Error')

Throws an error that has an HTTP status code. These errors are public-friendly, therefore their message can be displayed on the API.

The message parameter can either be a string or an object. For example,

let err = utils.httpError(404, { userMessage: "This product was not found. Please try other products" });

Then, on the client you will be able to do err.userMessage providing that you use our errorHandler(). Otherwise, you'll need to access your custom object via the data attribute of the error object: err.data.userMessage

// if you are using the error handler above, you can do something like this in
// any of your API endpoint
router.get("/users/:id", async (req, res, next) => {
  try {
    let user = await getUser(req.params.id);

    if (!user) {
      return next(utils.httpError(404, "Not found"));
    }
  } catch (err) {
    next(err);
  }
});

serveCSV

serveCSV(res, filename, rows)

returns a downloadable csv file built from "rows" which is an array of objects.

router.get("/data", async (req, res, next) => {
  let data = [{ name: "Test 0", age: 3 }, { name: "Test 1", age: 4 }];

  return utils.serveCSV(res, "data.csv", data);
});

hc

hc(app)

installs a health check route (/public/hc)

utils.hc(app);

expressjs-utils's People

Contributors

joejean avatar mingwho avatar nerac avatar odino avatar saadb94 avatar saarahhuda avatar tandalf avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

greenat92 medinae

expressjs-utils's Issues

Join your team

Hello guys,
I came across your LinkedIn profile for a job application and I came here to see your work and understand your dev environment more.
Honestly, you're doing a great job and I like the team structure a lot and that's encouraged me to learn more about your organization.
Based on my experience as Co-Founder and Tech Leader at Binary Torch Sdn. Bhd. and MySenior, I believe I could be a good fit to join your team.
Recently I moved to Dubai to get married and that forced me to leave my old job in Malaysia.
I have ~5 years of experience in software development (specifically web and mobile development) and I have a solid background of development life cycle since I was leading the tech stack of the companies I work with.

Please let me know if you’d be open to a conversation to discuss this position. I’m happy to provide you with any additional information you might need. I look forward to hearing from you. Also, you can take a look at my Github profile to see my latest open-source projects :)

Best regards,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.