npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

web-middlewares

v0.2.2

Published

Reusable middlewares and utils for Express.js

Downloads

2

Readme

Reusable middlewares, utils, and helper functions for Express.js

npm Version Build Status

Why?

  • Reuse implies efficiency
  • Save your time from copying Express.js middlewares
  • Encapsulate all related dependencies so that to create a more cleaner repo

Usages

Connect to the server

Focus on your routes and business logic:

import { connect } from 'web-middlewares';

const listener = connect(3000, server => {
  server.get('/', (req, res) => {
    res.send('Hello World');
  });
});

listener.then(info => log(info));

How can it save your time?


export default (port, done) => {
 // Prepend neccessary middlewares before matching any routes
  middleware(server);

  // Handle external middlewares
  done(server);

  // Append middlewares that catches remaining requests
  errorHandler(server);

  // Return a promise so that external service can execute post action after the server started
  return listener(server);
};

Express Middlewares

You can use different middleware in a flexible way:

import express from 'express';
import { middlewares } from 'web-middlewares';

const server = express();
const { middleware, errorHandler, listener } = middlewares;

middleware(server);

// ... the rest of the logic

errorHandler(server)
listener(server).then(info => log(info));

The middleware helper functions have the most commonly needed middlewares:

export default server => {
  server.use(morgan('common'));
  server.use(bodyParser.urlencoded({ extended: true }));
  server.use(bodyParser.json());
  server.use(methodOverride());
  server.use(compression());
};

CURD Creators

Encapsulate most reusable CURD actions into separated modules

import { curd } from 'web-middlewares';
const { actionCreator, modelCreator, routeCreator } = curd;

Example of actionCreator.js

export default Model => ({
  list: (req, res) => {
    Model.find().sort('-creation_date').exec((err, result) => {
      if (err) {
        res.status(500).send(err);
        return;
      }

      res.json({ result });
    });
  },

  // ... the rest of actions
});

Example of routeCreator.js

export default (routeName, action) => {
  router
    .get(`/${routeName}`, action.list)
    .get(`/${routeName}/:id`, action.get)
    .post(`/${routeName}`, action.new)
    .put(`/${routeName}/:id`, action.update)
    .delete(`/${routeName}/:id`, action.delete);

  return router;
};

Example of modelCreator.js

You can define any additional schema to that mongoose scheme:

const DEFAULT_SCHEMA = {
  created_at: { type: 'Date', default: Date.now, required: false },
  updated_at: { type: 'Date', default: Date.now, required: false },
};

export default (schema = {}) => {
  if (isEmpty(schema)) {
    throw new ArgumentNullError('schema');
  }

  return new mongoose.Schema(Object.assign({}, schema, DEFAULT_SCHEMA));
};

By doing this you can use custom method of mongoose schema before initializing it as a mongoose model.

const userModel = mongoose.model('User', modelCreator({
  email: String,
  name: String,
}));

Utils

import { utils } from 'web-middlewares';
const { connectDb, seedData, dropDb } = utils;

Connecting Database

A Promise handler will be returned by a given MongoDB url:

connectDb(<MONGODB_URL>).then(info => log(info));

Seeding data to database

It will clean up your database and pass each records to Promise.all for resolving.

seedData(userModel, [
  { email: '[email protected]', name: 'George Jor' },
  { email: '[email protected]', name: 'Jorge' }
]).then(info => log(info));;

Drop Connection

Normally used after running each test cases:

dropDb().then(info => log(info));